package com.moody.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.DefaultValueProcessor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.moody.calculator.DebtRatingCalculator;
import com.moody.hibernate.dao.PdHDAO;
import com.moody.hibernate.domain.AdjValue;
import com.moody.hibernate.domain.AdjValueId;
import com.moody.hibernate.domain.CodeLib;
import com.moody.hibernate.domain.CollateralInfo;
import com.moody.hibernate.domain.CustInfo;
import com.moody.hibernate.domain.CustLimit;
import com.moody.hibernate.domain.DebtCollateral;
import com.moody.hibernate.domain.DebtInfo;
import com.moody.hibernate.domain.IndInfo;
import com.moody.hibernate.domain.LgdH;
import com.moody.hibernate.domain.MainscaleHis;
import com.moody.hibernate.domain.MainscaleInfo;
import com.moody.hibernate.domain.ModelHis;
import com.moody.hibernate.domain.ModelInfo;
import com.moody.hibernate.domain.ModelLevel;
import com.moody.hibernate.domain.OrgInfo;
import com.moody.hibernate.domain.PdH;
import com.moody.hibernate.domain.QuaValue;
import com.moody.hibernate.domain.QuaValueId;
import com.moody.hibernate.domain.RatioValue;
import com.moody.hibernate.domain.RatioValueId;
import com.moody.hibernate.domain.ReportData;
import com.moody.hibernate.domain.ReportList;
import com.moody.hibernate.domain.UserInfo;
import com.moody.init.DataDictionary;
import com.moody.init.ParamModelInit;
import com.moody.init.ReportItemInit;
import com.moody.init.ReportModelInit;
import com.moody.service.CustomerService;
import com.moody.service.ModelService;
import com.moody.service.ObligationService;
import com.moody.service.RatingService;
import com.moody.service.RiskAppService;
import com.moody.service.SystemService;
import com.moody.util.CalendarUtil;
import com.moody.util.FormatUtil;

/*
 * Copyright © Moody analytics   
 *
 * @Title: RatingController.java 
 * @Package： com.moody.web 
 * @author： Fuqiang Wang
 * @Description: 评级管理：核心功能
 * @date： 2012-3-16 上午10:42:32
 * @Modified by: Fuqiang Wang 
 * @version V1.0   
 */

@Controller
@RequestMapping("/rating")
public class RatingController {
	private static final Logger log = LoggerFactory.getLogger(RatingController.class);
	WebApplicationContext web = ContextLoader.getCurrentWebApplicationContext();
	ServletContext context = web.getServletContext();  
	WebApplicationContext ctx  = WebApplicationContextUtils.getWebApplicationContext(context);
	private PdHDAO pdhDAO = PdHDAO.getFromApplicationContext(ctx);
	
	@Resource
	private RatingService ratingService;
	@Resource
	private CustomerService customerService;
	@Resource
	private ObligationService obligationService;
	@Resource
	private ModelService modelService;
	@Resource
	private RiskAppService riskAppService;
	@Resource
	private SystemService systemService;
	
	
	//for test
	@RequestMapping("/insertPD")
	public void insertPD(HttpServletRequest request,HttpServletResponse response){
		PdH pdh = new PdH();
		pdh.setCustId("222");
		pdh.setPhaseLevel("AAA");
		//log.info(pdh.getPhaseLevel());
		//log.info(pdh.getCustId());
		pdhDAO.save(pdh);
	}
	
	@RequestMapping("/loadTree")
	public void loadTree(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		////log.info("load tree");
		String s = "{\"cls\":\"folder\",\"id\":10,\"leaf\":false,\"children\":[{\"cls\":\"file\",\"id\":11,\"leaf\":true,\"children\":null,\"text\":\"S600\"},{\"cls\":\"file\",\"id\":12,\"leaf\":true,\"children\":null,\"text\":\"SLK200\"}],\"text\":\"Benz\"}";

		JSONObject myCustJO=JSONObject.fromObject(s);
		out.print(myCustJO);
		////log.info("JSON data: "+myCustJO);
	}

	//列出每个客户的最新评级信息，按照评级状态和时间排序
	@RequestMapping("/listSortedPD")
	public void listSortedPD(HttpServletRequest request,HttpServletResponse response) throws IOException, ParseException{
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		UserInfo user = (UserInfo)request.getSession().getAttribute("logonUser");
		String userId = user.getUserId();
		String orgId = user.getBelongorg();
		List<CustInfo> custList = new ArrayList<CustInfo>();
		List<PdH> pdHlist = new ArrayList<PdH>();
		
		//标记是零售还是对公
		String flag = request.getParameter("flag");
		//首先添加普通客户的信息
		if(flag!=null && flag.equals("1")){
			custList = customerService.findAllByCustType("", userId, orgId);
			pdHlist = ratingService.listCustSortedRatingByUser(userId,orgId,false);
		}
		//其次将零售客户加入列表中
		else if(flag != null && flag.equals("0")){
			List<IndInfo> indList = customerService.findAllIndCustomer(userId,orgId);
			pdHlist = ratingService.listCustSortedRatingByUser(userId,orgId,true);
			for(IndInfo indInfo : indList){
				CustInfo cust = new CustInfo();
				cust.setCustId(indInfo.getCustId());
				cust.setCustName(indInfo.getCustName());
				cust.setExposureType(indInfo.getExposureType());
				custList.add(cust);
			}
		}
		
		Integer totalSize = custList.size();
		//查询该用户下所见客户的最新评级信息
		//pdHlist = ratingService.listCustSortedRating();
		
		
		
		//封装JSON需要的结构，包含基本信息和评级信息
		List<Map<String,Object>> ratingList = new ArrayList<Map<String,Object>>();
		
		//每个客户获取其基本信息和评级信息
		//已评级
		for(PdH p : pdHlist){
			if(p.getPhaseStat() == null || p.getPhaseStat().equals(PdH.INVALIDATE))continue;
			if(p.getModelId() == null || p.getModelId().equals("")) continue;
			Map<String, Object> map = new HashMap<String,Object>();
			CustInfo custInfo = findCustInList(p.getCustId(),custList);
			if(custInfo != null){

				if(custInfo.getIndustryType() != null && !custInfo.getIndustryType().equals("")){
					custInfo.setIndustryType(DataDictionary.getInstance().getNameByCodeAndId("IndustryType", custInfo.getIndustryType()));
				}
				if(custInfo.getCustType() != null && !custInfo.getCustType().equals("")){
					custInfo.setCustType(DataDictionary.getInstance().getNameByCodeAndId("CustType", custInfo.getCustType()));
				}
				if(custInfo.getExposureType()!=null && !custInfo.getExposureType().equals("")){
					//custInfo.setExposureType(DataDictionary.getInstance().getNameByCodeAndId("ExposureType", custInfo.getExposureType()));
				}
				map.put("custInfo", custInfo);
				//设定评级结果
				p.setPhaseLevel(getLevel(p));
				p.setPhaseStat(DataDictionary.getInstance().getNameByCodeAndId("PhaseStat", p.getPhaseStat()));
				//如果是零售客户
				ModelHis model = modelService.findModelHisById(p.getModelId());
				if(model.getModelKind1().equals("04") && p.getPhaseLevel()!=null && p.getPhaseLevel().contains("0")){
					p.setPhaseLevel(DataDictionary.getInstance().getNameByCodeAndId("IndSystemResult", p.getPhaseLevel()));
				}
				if(p.getFirstUserId() != null && systemService.findUserById(p.getFirstUserId())!=null){
					p.setFirstUserId(systemService.findUserById(p.getFirstUserId()).getUsername());
				}
				if(p.getFirstOrgId() != null && systemService.findOrgById(p.getFirstOrgId())!=null) {
					p.setFirstOrgId(systemService.findOrgById(p.getFirstOrgId()).getOrgname());
				}
				
				if(p.getConfirmDate()!=null && !("").equals(p.getConfirmDate())){
					String confirmDate = p.getConfirmDate();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");   
	                Calendar cd = Calendar.getInstance();   
	                cd.setTime(sdf.parse(confirmDate));   
	                cd.add(Calendar.YEAR, 1);
	                cd.add(Calendar.DATE, -1);//减少一天  
					String endDate = sdf.format(cd.getTime());  
					p.setEndDate(endDate);
				}

				////log.info(p.getFirstUserId());
				map.put("custPD", p);
	
				CustLimit custLimit = riskAppService.findCustLimitByCustId(custInfo.getCustId());

				if(custLimit.getFinalLimit()!= null){
					double finalLimit = custLimit.getFinalLimit();
					custLimit.setFinalLimitString(""+custLimit.getFinalLimit().intValue());
				}
				
				map.put("custLimit", custLimit);
				
				ratingList.add(map);
				//如果包含此对象，将其移除
				if(custList.contains(custInfo))
					custList.remove(custInfo);
			}
		}
		
		//对于尚未评级的客户，将其置为未评级
		for(CustInfo custInfo : custList){
			Map<String, Object> map = new HashMap<String,Object>();
			
			if(custInfo.getIndustryType() != null && !custInfo.getIndustryType().equals("")){
				custInfo.setIndustryType(DataDictionary.getInstance().getNameByCodeAndId("IndustryType", custInfo.getIndustryType()));
			}
			if(custInfo.getCustType() != null && !custInfo.getCustType().equals("")){
				custInfo.setCustType(DataDictionary.getInstance().getNameByCodeAndId("CustType", custInfo.getCustType())); 
			}
			if(custInfo.getExposureType()!=null && !custInfo.getExposureType().equals("")){
				//custInfo.setExposureType(DataDictionary.getInstance().getNameByCodeAndId("ExposureType", custInfo.getExposureType()));
			}
			map.put("custInfo", custInfo);
			PdH p = new PdH();
			p.setPhaseStat(DataDictionary.getInstance().getNameByCodeAndId("PhaseStat", PdH.NOT_RATTING));
			if(p.getFirstUserId() != null )p.setFirstUserId(systemService.findUserById(p.getFirstUserId()).getUsername());
			if(p.getFirstOrgId() != null) {
				p.setFirstOrgId(systemService.findOrgById(p.getFirstOrgId()).getOrgname());
			}
			map.put("custPD", p);
			CustLimit custLimit = riskAppService.findCustLimitByCustId(custInfo.getCustId());
			if(custLimit==null){
				custLimit = new CustLimit();
				custLimit.setCustId(custInfo.getCustId());
				custLimit.setCustName(custInfo.getCustName());
				riskAppService.insertCustLimit(custLimit);
			}
			if(custLimit.getFinalLimit()!= null){
				double finalLimit = custLimit.getFinalLimit();
				custLimit.setFinalLimitString(""+custLimit.getFinalLimit().intValue());
			}
			map.put("custLimit", custLimit);
			ratingList.add(map);
		}
		//printDurationTime("尚未评级的for");
//		long t5 = Calendar.getInstance().getTimeInMillis();
//		log.info(t5-t4+"ms");
		
		customerService.sortByPDState(ratingList);
		//printDurationTime("sortByPDState");
		
		//分页
		Integer start = Integer.parseInt(request.getParameter("start"));
		Integer limit = Integer.parseInt(request.getParameter("limit"));
		
		List<Map<String,Object>> pageList;
		if(ratingList.size()>start+limit)
			pageList = ratingList.subList(start, limit+start); 
		else
			pageList = ratingList.subList(start,ratingList.size());
		
		Map<String, Object> myCustMap = new HashMap<String, Object>(3);
		myCustMap.put("total", totalSize);
		myCustMap.put("resultData", pageList);
		JSONObject myCustJO=JSONObject.fromObject(myCustMap);
		out.print(myCustJO);
		
		////log.info("JSON数据："+myCustJO);
	}
	
//	static long lastTime = 0;
//	public void printDurationTime(String functionName){
//		if(lastTime == 0) lastTime = Calendar.getInstance().getTimeInMillis();
//		long currentTime = Calendar.getInstance().getTimeInMillis();
//		log.info(functionName + ":" +(currentTime - lastTime));
//		lastTime = currentTime;
//	}
	//列出每个客户的最新评级信息，按照评级状态和时间排序
	//首页中的关注客户，包含评级结果较低的和评级即将到期的客户
	@RequestMapping("/listSortedPDFocusCustomer")
	public void listSortedPDFocusCustomer(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ParseException{
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		
		UserInfo user = (UserInfo)request.getSession().getAttribute("logonUser");
		String userId = user.getUserId();
		String orgId = user.getBelongorg();
		
		//首先添加普通客户的信息
		List<CustInfo> custList = customerService.findAllByCustType("", userId, orgId);
		//其次将零售客户加入列表中
		List<IndInfo> indList = customerService.findAllIndCustomer(userId,orgId);
		for(IndInfo indInfo : indList){
			CustInfo cust = new CustInfo();
			cust.setCustId(indInfo.getCustId());
			cust.setCustName(indInfo.getCustName());
			custList.add(cust);
		}
		
		Integer totalSize = custList.size();
		List<PdH> pdHlist;
		pdHlist = ratingService.listCustSortedRatingByConfirmDate();
		
		//封装JSON需要的结构，包含基本信息和评级信息
		List<Map<String,Object>> ratingList = new ArrayList<Map<String,Object>>();
		
		//每个客户获取其基本信息和评级信息
		//已评级
		for(PdH p : pdHlist){
			Map<String, Object> map = new HashMap<String,Object>();
			CustInfo custInfo = findCustInList(p.getCustId(),custList);
			if(p.getModelId() == null || p.getModelId().equals("")) continue;
			
			//评级较低的和即将到期的客户
			//TODO 请定义评级较低的指的是?
			if(custInfo != null && PdH.CONFIRM_FINISH.equals(p.getPhaseStat())
					&& (!getLevel(p).contains("A"))){

				if(custInfo.getExposureType()!=null && !custInfo.getExposureType().equals("")){
					//custInfo.setExposureType(DataDictionary.getInstance().getNameByCodeAndId("ExposureType", custInfo.getExposureType()));
				}
				map.put("custInfo", custInfo);
				//设定评级结果
				p.setPhaseLevel(getLevel(p));
				p.setPhaseStat(DataDictionary.getInstance().getNameByCodeAndId("PhaseStat", p.getPhaseStat()));
				
				//如果是零售客户
				ModelHis model = modelService.findModelHisById(p.getModelId());
				if(model.getModelKind1().equals("04") && p.getPhaseLevel()!=null && p.getPhaseLevel().contains("0")){
					if(p.getPhaseLevel().equals("01"))continue;// 对于准入的零售客户，不在关注列表中
					p.setPhaseLevel(DataDictionary.getInstance().getNameByCodeAndId("IndSystemResult", p.getPhaseLevel()));
				}
				
				if(p.getConfirmDate()!=null && !("").equals(p.getConfirmDate())){
					String confirmDate = p.getConfirmDate();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");   
	                Calendar cd = Calendar.getInstance();   
	                cd.setTime(sdf.parse(confirmDate));   
	                cd.add(Calendar.YEAR, 1);
	                cd.add(Calendar.DATE, -1);//减少一天  
					String endDate = sdf.format(cd.getTime());  
					p.setEndDate(endDate);
				}
				
				if(p.getFirstUserId() != null && systemService.findUserById(p.getFirstUserId())!=null){
					p.setFirstUserId(systemService.findUserById(p.getFirstUserId()).getUsername());
				}

				//log.info(p.getFirstUserId());
				map.put("custPD", p);
	
				CustLimit custLimit = riskAppService.findCustLimitByCustId(custInfo.getCustId());
				map.put("custLimit", custLimit);
				
				ratingList.add(map);
				//如果包含此对象，将其移除
				if(custList.contains(custInfo))
					custList.remove(custInfo);
			}
		}
		
		//分页
		Integer start = Integer.parseInt(request.getParameter("start"));
		Integer limit = Integer.parseInt(request.getParameter("limit"));
		
		List<Map<String,Object>> pageList;
		if(ratingList.size()>start+limit)
			pageList = ratingList.subList(start, limit+start); 
		else
			pageList = ratingList.subList(start,ratingList.size());
		
		Map<String, Object> myCustMap = new HashMap<String, Object>(3);
		myCustMap.put("total", ratingList.size());
		myCustMap.put("resultData", pageList);
		JSONObject myCustJO=JSONObject.fromObject(myCustMap);
		out.print(myCustJO);
		
		////log.info("JSON数据："+myCustJO);
	}
	
	//列出每个客户的最新评级信息，按照评级状态和时间排序。结果用于主页的工作列表显示
	@RequestMapping("/listSortedPDOnMain")
	public void listSortedPDOnMain(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ParseException{
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		
		UserInfo user = (UserInfo)request.getSession().getAttribute("logonUser");
		String userId = user.getUserId();
		String orgId = user.getBelongorg();
		
		//首先添加普通客户的信息
		List<CustInfo> custList = customerService.findAllByCustType("", userId, orgId);
		//其次将零售客户加入列表中
		List<IndInfo> indList = customerService.findAllIndCustomer(userId,orgId);
		for(IndInfo indInfo : indList){
			CustInfo cust = new CustInfo();
			cust.setCustId(indInfo.getCustId());
			cust.setCustName(indInfo.getCustName());
			custList.add(cust);
		}
		
		Integer totalSize = custList.size();
		List<PdH> pdHlist;
		pdHlist = ratingService.listCustSortedRating();
		
		//封装JSON需要的结构，包含基本信息和评级信息
		List<Map<String,Object>> ratingList = new ArrayList<Map<String,Object>>();
		
		//每个客户获取其基本信息和评级信息
		//已评级
		for(PdH p : pdHlist){
			if(p.getModelId() == null || p.getModelId().equals("")) continue;
			Map<String, Object> map = new HashMap<String,Object>();
			CustInfo custInfo = findCustInList(p.getCustId(),custList);
			if(custInfo != null){

				if(custInfo.getExposureType()!=null && !custInfo.getExposureType().equals("")){
					//custInfo.setExposureType(DataDictionary.getInstance().getNameByCodeAndId("ExposureType", custInfo.getExposureType()));
				}
				map.put("custInfo", custInfo);
				//设定评级结果
				p.setPhaseLevel(getLevel(p));
				p.setPhaseStat(DataDictionary.getInstance().getNameByCodeAndId("PhaseStat", p.getPhaseStat()));
				
				//如果是零售客户
				if(p.getModelId() == null || p.getModelId().equals(""))continue;
				ModelHis model = modelService.findModelHisById(p.getModelId());
				if(model.getModelKind1().equals("04") && p.getPhaseLevel()!=null && p.getPhaseLevel().contains("0")){
					p.setPhaseLevel(DataDictionary.getInstance().getNameByCodeAndId("IndSystemResult", p.getPhaseLevel()));
				}
				if(p.getFirstUserId() != null && systemService.findUserById(p.getFirstUserId())!=null)
					p.setFirstUserId(systemService.findUserById(p.getFirstUserId()).getUsername());
				
				if(p.getConfirmDate()!=null && !("").equals(p.getConfirmDate())){
					String confirmDate = p.getConfirmDate();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");   
	                Calendar cd = Calendar.getInstance();   
	                cd.setTime(sdf.parse(confirmDate));   
	                cd.add(Calendar.YEAR, 1);
	                cd.add(Calendar.DATE, -1);//减少一天  
					String endDate = sdf.format(cd.getTime());  
					p.setEndDate(endDate);
				}
				
				map.put("custPD", p);
	
				CustLimit custLimit = riskAppService.findCustLimitByCustId(custInfo.getCustId());
				map.put("custLimit", custLimit);
				
				ratingList.add(map);
				//如果包含此对象，将其移除
				if(custList.contains(custInfo))
					custList.remove(custInfo);
			}
		}
		//对于尚未评级的客户，将其置为未评级
		for(CustInfo custInfo : custList){
			Map<String, Object> map = new HashMap<String,Object>();
			
			if(custInfo.getExposureType()!=null && !custInfo.getExposureType().equals("")){
				//custInfo.setExposureType(DataDictionary.getInstance().getNameByCodeAndId("ExposureType", custInfo.getExposureType()));
			}
			map.put("custInfo", custInfo);
			PdH p = new PdH();
			p.setPhaseStat(DataDictionary.getInstance().getNameByCodeAndId("PhaseStat", PdH.NOT_RATTING));
			if(p.getFirstUserId() != null )p.setFirstUserId(systemService.findUserById(p.getFirstUserId()).getUsername());
			map.put("custPD", p);
			CustLimit custLimit = riskAppService.findCustLimitByCustId(custInfo.getCustId());
			if(custLimit==null){
				custLimit = new CustLimit();
				custLimit.setCustId(custInfo.getCustId());
				custLimit.setCustName(custInfo.getCustName());
				riskAppService.insertCustLimit(custLimit);
			}
			map.put("custLimit", custLimit);
			ratingList.add(map);
		}
		
		
		/**
		 * custRole:
		 * 1-客户经理岗。列出：尚未评级，发起人初评阶段
		 * 2-复评岗。列出：待复评阶段
		 * 3-审核岗。列出：待审核阶段
		 * 4-人定岗。列出：待认定阶段
		 */
		int custRole = 0;
		String accessURL = (String) request.getSession().getAttribute("accessURL");
		if(accessURL.contains("CustomerRating_FirstPD")) custRole = 1;
		else if(accessURL.contains("CustomerRating_FirstVerifyPD"))custRole = 2;
		else if(accessURL.contains("CustomerRating_SecondPD"))custRole = 3;
		else if(accessURL.contains("CustomerRating_ConfirmPD"))custRole = 4;
		
		//根据不同角色对应的不同评级阶段来确定显示哪条客户
		List<Map<String,Object>> pageListAll = new ArrayList<Map<String,Object>>();
		
		for(Map<String,Object> item :ratingList){
			String phaseStatString = ((PdH)item.get("custPD")).getPhaseStat();
			String p0 = DataDictionary.getInstance().getNameByCodeAndId("PhaseStat", PdH.NOT_RATTING);
			String p1 = DataDictionary.getInstance().getNameByCodeAndId("PhaseStat", PdH.FIRST_RATTING);
			String p2 = DataDictionary.getInstance().getNameByCodeAndId("PhaseStat", PdH.FIRST_VERIFY_RATTING);
			String p3 = DataDictionary.getInstance().getNameByCodeAndId("PhaseStat", PdH.SECOND_RATTING);
			String p4 = DataDictionary.getInstance().getNameByCodeAndId("PhaseStat", PdH.CONFIRM_RATTING);
//			String p5 = DataDictionary.getInstance().getNameByCodeAndId("PhaseStat", PdH.CONFIRM_FINISH);
			
			
			if(((p0.equals(phaseStatString) || p1.equals(phaseStatString)) && custRole == 1) || 
					(p2.equals(phaseStatString) && custRole == 2) ||
					(p3.equals(phaseStatString) && custRole == 3) ||
					(p4.equals(phaseStatString) && custRole == 4) ){
				pageListAll.add(item);
			}
		}
		//分页
		Integer start = Integer.parseInt(request.getParameter("start"));
		Integer limit = Integer.parseInt(request.getParameter("limit"));
		
		List<Map<String,Object>> pageList;
		if(pageListAll.size()>start+limit)
			pageList = pageListAll.subList(start, limit+start); 
		else
			pageList = pageListAll.subList(start,pageListAll.size());
		
		Map<String, Object> myCustMap = new HashMap<String, Object>(3);
		myCustMap.put("total", pageListAll.size());
		myCustMap.put("resultData", pageList);
		JSONObject myCustJO=JSONObject.fromObject(myCustMap);
		out.print(myCustJO);
		
		////log.info("JSON数据："+myCustJO);
	}
	
	
	private CustInfo findCustInList(String custId, List<CustInfo> custList) {
		CustInfo  result = null;
		for(CustInfo custInfo : custList){
			if(custInfo.getCustId().equals(custId))
				result =  custInfo;
		}
		
		return result;
	}
	
	//根据某PD获得评级结果：评级结果”的含义与“评级状态”相对应：
	//待审核对应的是初评结果, 待认定对应的是审核评级结果,已认定对应的是认定评级结果，
	private String getLevel(PdH p) {
		String modelId = p.getModelId();
		ModelHis model = modelService.findModelHisById(modelId);
		
		//如果是零售
		if(!model.getModelKind1().equals("04")){
			if(p.getPhaseStat() == null) return null;
			if(p.getPhaseStat().equals("02"))
				return p.getFirstPdlevel();
			else if(p.getPhaseStat().equals("03"))
				return p.getFirstVerifyPdlevel();
			else if(p.getPhaseStat().equals("04"))
				return p.getSecondPdlevel();
			else if(p.getPhaseStat().equals("06"))
				return p.getConfirmPdlevel();
			else
				return p.getSystemPdlevel();
		}else{
			if(p.getPhaseStat() == null) return null;
			else if(p.getPhaseStat().equals("02"))
				return p.getFirstPdlevel();
			else
				return p.getSecondPdlevel();
		}
	}
	
	//查询客户
	@RequestMapping("/findCustomer")
	public void findCustomer(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ParseException{
		
		String conditionKey = request.getParameter("condition");
		String conditionValue = request.getParameter("keyword");
		String flag = request.getParameter("flag");
		
		List<CustInfo> custList = new ArrayList<CustInfo>(); 
		List<PdH> pdHlist;
		
		UserInfo user = (UserInfo) request.getSession().getAttribute("logonUser");
		String userId = user.getUserId();
		String orgId = user.getBelongorg();
		Map<String,String> condition = new LinkedHashMap<String,String>();
		if(conditionKey.equals("custId")) conditionKey = "custNo";//转换成按照客户号查询
		
		//初评人、初评机构的情况不使用事先查询，使用事后过滤
		if(conditionKey != null && !conditionKey.equals("firstUserName") && !conditionKey.equals("firstOrgName")) 
			condition.put(conditionKey, conditionValue);
		
		if(flag!=null && flag.equals("1")){
			custList = customerService.findCustByCondition(condition, userId, orgId);
			pdHlist = ratingService.listCustSortedRatingByUser(userId, orgId, false);
		}else{
			List<IndInfo> indCustList = customerService.findIndCustByCondition(condition, userId, orgId);
			pdHlist = ratingService.listCustSortedRatingByUser(userId, orgId, true);
			for(IndInfo indInfo : indCustList){
				CustInfo cust = new CustInfo();
				cust.setCustId(indInfo.getCustId());
				cust.setCustName(indInfo.getCustName());
				cust.setExposureType(indInfo.getExposureType());
				custList.add(cust);
			}
		}
		
		Integer totalSize = custList.size();
		
		//封装JSON需要的结构，包含基本信息和评级信息
		List<Map<String,Object>> ratingList = new ArrayList<Map<String,Object>>();
		
		//每个客户获取其基本信息和评级信息
		//已评级
		for(PdH p : pdHlist){
			if(p.getModelId() == null || p.getModelId().equals("")) continue;
			if(p.getPhaseStat() == null || p.getPhaseStat().equals(PdH.INVALIDATE))continue;
			
			Map<String, Object> map = new HashMap<String,Object>();
			CustInfo custInfo = findCustInList(p.getCustId(),custList);
			if(custInfo != null){
				if(custInfo.getExposureType()!=null){
					//custInfo.setExposureType(DataDictionary.getInstance().getNameByCodeAndId("ExposureType", custInfo.getExposureType()));
				}

				if(custInfo.getIndustryType() != null && !custInfo.getIndustryType().equals("")){
					custInfo.setIndustryType(DataDictionary.getInstance().getNameByCodeAndId("IndustryType", custInfo.getIndustryType()));
				}
				map.put("custInfo", custInfo);
				//设定评级结果
				p.setPhaseLevel(getLevel(p));
				p.setPhaseStat(DataDictionary.getInstance().getNameByCodeAndId("PhaseStat", p.getPhaseStat()));
				if(p.getFirstUserId()!=null && systemService.findUserById(p.getFirstUserId()) != null)
					p.setFirstUserId(systemService.findUserById(p.getFirstUserId()).getUsername());
				else 
					p.setFirstUserId("");
				if(p.getFirstOrgId() != null) {
					p.setFirstOrgId(systemService.findOrgById(p.getFirstOrgId()).getOrgname());
				}
				if(p.getConfirmDate()!=null && !("").equals(p.getConfirmDate())){
					String confirmDate = p.getConfirmDate();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");   
	                Calendar cd = Calendar.getInstance();   
	                cd.setTime(sdf.parse(confirmDate));   
	                cd.add(Calendar.YEAR, 1);
	                cd.add(Calendar.DATE, -1);//减少一天  
					String endDate = sdf.format(cd.getTime());  
					p.setEndDate(endDate);
				}
				//p.setPhaseLevel(getLevel(p));
				map.put("custPD", p);

				ratingList.add(map);
			}
			
			//如果包含此对象，将其移除
			if(custList.contains(custInfo))
				custList.remove(custInfo);
		}
		//对于尚未评级的客户，将其置为未评级
		for(CustInfo custInfo : custList){
			Map<String, Object> map = new HashMap<String,Object>();
			if(custInfo.getExposureType()!=null){
				//custInfo.setExposureType(DataDictionary.getInstance().getNameByCodeAndId("ExposureType", custInfo.getExposureType()));
			}
			if(custInfo.getIndustryType() != null && !custInfo.getIndustryType().equals("")){
				custInfo.setIndustryType(DataDictionary.getInstance().getNameByCodeAndId("IndustryType", custInfo.getIndustryType()));
			}
			map.put("custInfo", custInfo);
			PdH p = new PdH();
			p.setPhaseStat(DataDictionary.getInstance().getNameByCodeAndId("PhaseStat", PdH.NOT_RATTING));
			map.put("custPD", p);
			ratingList.add(map);
		}
		
		if(conditionKey != null && (conditionKey.equals("firstUserName") || conditionKey.equals("firstOrgName"))){
			Iterator<Map<String,Object>> it = ratingList.iterator();
			while(it.hasNext()){
				Map<String,Object> itemMap = it.next();
				PdH custPD = (PdH)(itemMap.get("custPD"));
				String firstUserId = custPD.getFirstUserId();
				String firstOrgId = custPD.getFirstOrgId();
				if(conditionKey.equals("firstUserName") && (firstUserId == null || (firstUserId != null && !firstUserId.contains(conditionValue)))) it.remove();
				else if(conditionKey.equals("firstOrgName") && (firstOrgId == null || (firstOrgId != null && !firstOrgId.contains(conditionValue)))) it.remove();
			}
		}
		
		//分页
		Integer start = Integer.parseInt(request.getParameter("start"));
		Integer limit = Integer.parseInt(request.getParameter("limit"));
		
		List<Map<String,Object>> pageList;
		if(ratingList.size()>start+limit)
			pageList = ratingList.subList(start, limit+start); 
		else
			pageList = ratingList.subList(start,ratingList.size());
		
		Map<String, Object> myCustMap = new HashMap<String, Object>(3);
		myCustMap.put("success", "true");
		myCustMap.put("total", totalSize);
		myCustMap.put("resultData", pageList);
		JSONObject myCustJO=JSONObject.fromObject(myCustMap);
		
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		response.getWriter().print(myCustJO);
		
	}

	
	//客户列表-->客户评级信息列表
	@RequestMapping("/showHistoryPDList")
	public String showHistoryPDList(HttpServletRequest request, 
			HttpServletResponse response){
		
		String custId = request.getParameter("CustId");
		
		CustInfo currentCust = new CustInfo();
		currentCust = customerService.findCustByCustId(custId);
		//如果是正常客户
		if(currentCust != null){
			request.getSession().removeAttribute("ratingCustId");
			request.getSession().setAttribute("ratingCustId", custId);
			
			request.getSession().removeAttribute("CustId");
			request.getSession().setAttribute("CustId", custId);
			request.getSession().removeAttribute("custInfo");
			request.getSession().setAttribute("custInfo", currentCust);

			request.getSession().removeAttribute("ratingCustName");
			request.getSession().setAttribute("ratingCustName", currentCust.getCustName());
			request.getSession().removeAttribute("ratingCustType");
			request.getSession().setAttribute("ratingCustType", DataDictionary.getInstance().getNameByCodeAndId("CustType", currentCust.getCustType()));
			request.getSession().removeAttribute("ratingIndustryType");
			request.getSession().setAttribute("ratingIndustryType", DataDictionary.getInstance().getNameByCodeAndId("IndustryType", currentCust.getIndustryType()));
			
			request.getSession().removeAttribute("ratingCust");
			request.getSession().setAttribute("ratingCust", currentCust);
			
			return "rating/CustomerRating_HistoryRating";
		}else{
		//如果是零售客户
			IndInfo indCust = customerService.findIndCustByCustId(custId);
			currentCust = new CustInfo();
			currentCust.setCustId(indCust.getCustId());
			currentCust.setCustNo(indCust.getCustNo());
			currentCust.setCustType("04");
			currentCust.setCustName(indCust.getCustName());
			currentCust.setExposureType(indCust.getExposureType());

			request.getSession().removeAttribute("custInfo");
			request.getSession().setAttribute("custInfo", currentCust);
			
			indCust = customerService.findIndCustByCustId(custId);
			request.getSession().removeAttribute("ratingCustId");
			request.getSession().setAttribute("ratingCustId", custId);
			
			request.getSession().removeAttribute("ratingCustName");
			request.getSession().setAttribute("ratingCustName", indCust.getCustName());		
			
			request.getSession().removeAttribute("ratingCust");
			request.getSession().setAttribute("ratingCust", currentCust);
			
			request.getSession().removeAttribute("ratingCustType");
			request.getSession().setAttribute("ratingCustType", DataDictionary.getInstance().getNameByCodeAndId("CustType", CustInfo.CUSTYPE_RETAIL));
			request.getSession().removeAttribute("ratingIndustryType");

			request.getSession().removeAttribute("indCustId");
			request.getSession().setAttribute("indCustId", custId);
			
			request.getSession().removeAttribute("ratingIndIDNo");
			request.getSession().setAttribute("ratingIndIDNo", indCust.getIdno());
			
			return "rating/CustomerRating_IndHistoryRating";
		}
		
	}

	//列出该客户的历史评级信息
	@RequestMapping("/listHistoryPD")
	public void listHistoryRating(HttpServletRequest request,HttpServletResponse response) throws IOException, ParseException{ 
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		
		//分页
		Integer start = Integer.parseInt(request.getParameter("start"));
		Integer limit = Integer.parseInt(request.getParameter("limit"));
		//评级的客户ID
		String ratingCustId = "";
		
		//判断是否是从客户管理过来的内部评级
		String isFromCustomer = request.getParameter("isFromCustomer");
		String isInd = request.getParameter("isInd");
		if(isFromCustomer!=null && !isFromCustomer.equals("")){
			ratingCustId = request.getSession().getAttribute("custId").toString();
		}else if(isInd!=null && !isInd.equals("")){
			ratingCustId = request.getSession().getAttribute("indCustId").toString();
		}
		else{
			if(request.getSession().getAttribute("ratingCustId")!=null)
				ratingCustId = request.getSession().getAttribute("ratingCustId").toString();
		}
		
		
		/*//test 
		ratingCustId = "111";*/
		//该客户的历史评级信息
		List<PdH> list;
		list = ratingService.findHistoryRatingPdH(ratingCustId);
		//分页
		List<PdH> pageList;
		if(list.size()>start+limit)
			pageList = list.subList(start, limit+start); 
		else
			pageList = list.subList(start,list.size());
		
		//将某些字段的code变成name
		for(PdH p : pageList){
			p.setPhaseStat(DataDictionary.getInstance().getNameByCodeAndId("PhaseStat", p.getPhaseStat()));
			
			if(p.getConfirmDate()!=null && !("").equals(p.getConfirmDate())){
				String confirmDate = p.getConfirmDate();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");   
                Calendar cd = Calendar.getInstance();   
                cd.setTime(sdf.parse(confirmDate));   
                cd.add(Calendar.YEAR, 1);
                cd.add(Calendar.DATE, -1);//减少一天  
				String endDate = sdf.format(cd.getTime());  
				p.setEndDate(endDate);
			}
			
			//如果是零售
			String secondPdLevel = p.getSecondPdlevel();
			if(secondPdLevel !=null && secondPdLevel.contains("0")){
				p.setSecondPdlevel(DataDictionary.getInstance().getNameByCodeAndId("IndSystemResult", secondPdLevel));
			}
			p.setModelId(modelService.findModelHisById(p.getModelId()).getModelName());
			if(p.getFirstUserId()!= null && systemService.findUserById(p.getFirstUserId()) != null)p.setFirstUserId(systemService.findUserById(p.getFirstUserId()).getUsername());
			if(p.getFirstOrgId() != null && systemService.findOrgById(p.getFirstOrgId()) != null)p.setFirstOrgId(systemService.findOrgById(p.getFirstOrgId()).getOrgname());
		}
		
		Map<String, Object> myCustMap = new HashMap<String, Object>(3);
		myCustMap.put("total", list.size());
		myCustMap.put("resultData", pageList);
		JSONObject myCustJO=JSONObject.fromObject(myCustMap);
		out.print(myCustJO);
		
		////log.info("JSON数据："+myCustJO);
	}
	
	//查找最新一期的评级
	@RequestMapping("/findNewestPD")
	public void findNewestPD(HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		//评级的客户ID
		String ratingCustId = "";
		if(request.getSession().getAttribute("ratingCustId")!=null)
			ratingCustId = request.getSession().getAttribute("ratingCustId").toString();
		
		List<PdH> list = ratingService.findHistoryRatingPdH(ratingCustId);
		PdH pd = null;
		
		if(list!=null && list.size()>0){
			pd = list.get(0);
		}
		
		JSONObject pdJO = JSONObject.fromObject(pd);
		response.setContentType("application/json; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(pdJO);
		
	}
	
	
	//发起评级，选择模板和风险暴露类型
	@RequestMapping("/addPD")
	public String addPD(HttpServletRequest request, 
			HttpServletResponse response){
		String custId = request.getSession().getAttribute("ratingCustId").toString();
		String exposureType = request.getParameter("exposureType");
		String modelId = request.getParameter("modelId");
		String reportDate = request.getParameter("reportDate");

		CustInfo cust = new CustInfo();
		cust = customerService.findCustByCustId(custId);
		IndInfo indCust = new IndInfo();
		//如果不是一般客户的话则去零售客户列表中找
		if(cust!=null){
			cust.setExposureType(exposureType);
		}else{
			indCust = customerService.findIndCustByCustId(custId);
			indCust.setExposureType(exposureType);
			//刷新ression：
			request.getSession().setAttribute("indCustId", indCust.getCustId());
			customerService.updateIndCustInfo(indCust);
		}

		if(cust!= null) customerService.updateCustInfo(cust);
		
		UserInfo user = (UserInfo) request.getSession().getAttribute("logonUser");
		
		PdH pd = new PdH();
		pd.setModelId(modelId);
		pd.setCustId(custId);
		pd.setReportDate(reportDate);
		pd.setFirstUserId(user.getUserId());
		pd.setFirstOrgId(user.getBelongorg());
		pd.setFirstDate(CalendarUtil.getCurrentDateStr());
		pd.setPhaseStat(PdH.NOT_RATTING);
		
		ratingService.invalidatePdH(custId);//将原进行中的评级失效
		ratingService.insertPdH(pd);
		
		
		//将最近一期的客户评级结果写入custInfo表中
		PdH recentPd = ratingService.findRecentPDByCustId(custId);
		if(recentPd!=null && cust!=null){
			cust.setCreditLevel(recentPd.getConfirmPdlevel());
			customerService.updateCustInfo(cust);
		}

		request.getSession().removeAttribute("modelId");
		request.getSession().setAttribute("usedModelId", modelId);
		

		request.getSession().removeAttribute("ratingPD");
		request.getSession().setAttribute("ratingPD",pd );
		
		request.getSession().removeAttribute("pdId");
		request.getSession().setAttribute("pdId", pd.getSerialNo());
		
		String modelName = modelService.findModelHisById(modelId).getModelName();
		request.getSession().removeAttribute("modelName");
		request.getSession().setAttribute("modelName", modelName);

		if(cust!=null){
			request.getSession().removeAttribute("reportDate");
			request.getSession().setAttribute("reportDate", reportDate);
		}
		request.getSession().removeAttribute("exposureType");
		request.getSession().setAttribute("exposureType", exposureType);

		ModelHis model = modelService.findModelHisById(modelId);
		//如果是零售客户
		if(model.getModelKind1().equals("04")){
			return "rating/CustomerRating_IndRatingProcess";
		}else{
			String kind2 = modelService.findModelHisById(modelId).getModelKind2();
			if(kind2.equals("0103") || kind2.equals("0105") || kind2.equals("0302"))
				return "rating/CustomerRating_RatingSpecialProcess";
			else return "rating/CustomerRating_RatingProcess";
		}
	}
	
	/*
	 * 评级列表——删除评级
	 */
	@RequestMapping("/deletePD")
	public void deleteCustomer(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String serialNo = request.getParameter("SerialNo");
		PdH pdh = ratingService.findPDById(serialNo);
		if(pdh!=null){
			pdhDAO.delete(pdh);
		}
		response.getWriter().print("{success:false}");

	}
	
	//客户列表-->客户的债项列表
	@RequestMapping("/showDebtList")	
	public String showDebtList(HttpServletRequest request, 
			HttpServletResponse response){
		String custId = request.getParameter("custId");
		
		CustInfo currentCust = new CustInfo();
		currentCust = customerService.findCustByCustId(custId);
		
		request.getSession().removeAttribute("ratingCustId");
		request.getSession().setAttribute("ratingCustId", custId);
		
		request.getSession().removeAttribute("ratingCustName");
		request.getSession().setAttribute("ratingCustName", currentCust.getCustName());
		
		return "rating/DebtRating_DebtList";
	}
	
	//列出该客户的历史评级信息
	@RequestMapping("/listDebt")
	public void listDebt(HttpServletRequest request,HttpServletResponse response) throws IOException{ 
		//评级的客户ID
		String ratingCustId = "";
		if(request.getSession().getAttribute("ratingCustId")!=null)
			ratingCustId = request.getSession().getAttribute("ratingCustId").toString();
		
		//找出该客户的所有债项信息
		List<DebtInfo> debtList = obligationService.findDebtByCustId(ratingCustId);
		
		//分页
		Integer start = Integer.parseInt(request.getParameter("start"));
		Integer limit = Integer.parseInt(request.getParameter("limit"));
		List<DebtInfo> pageList;
		if(debtList.size()>start+limit)
			pageList = debtList.subList(start, limit+start); 
		else
			pageList = debtList.subList(start,debtList.size());
		
		//将某些字段的code转化为name展示
		
		for(DebtInfo debtInfo : pageList){
			if(debtInfo.getBusinessKind() != null && debtInfo.getBusinessKind().length() >= 2)debtInfo.setBusinessKind(DataDictionary.getInstance().getNameByCodeAndId("BusinessKind", debtInfo.getBusinessKind()));
			debtInfo.setCurrency(DataDictionary.getInstance().getNameByCodeAndId("Currency", debtInfo.getCurrency()));
			debtInfo.setDebtType(DataDictionary.getInstance().getNameByCodeAndId("DebtType", debtInfo.getDebtType()));
			debtInfo.setGuarantyKind(DataDictionary.getInstance().getNameByCodeAndId("GuarantyKind", debtInfo.getGuarantyKind()));
			debtInfo.setGroupLoanType(DataDictionary.getInstance().getNameByCodeAndId("YesNo", debtInfo.getGroupLoanType()));
			if(debtInfo.getLgd()!= null) debtInfo.setLgd(debtInfo.getLgd() * 100);
			//从lGD表中获得余额
			//TODO 
		}
		
		
		//转化为JSON
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		Map<String, Object> myCustMap = new HashMap<String, Object>(3);
		myCustMap.put("total", debtList.size());
		myCustMap.put("resultData", pageList);
		JSONObject myCustJO=JSONObject.fromObject(myCustMap);
		out.print(myCustJO);
		
		////log.info("JSON数据："+myCustJO);
	}
	
	//获取某笔债项的详情
	//获取单一债项
	@RequestMapping("/getDebt")
	public void getDebt(HttpServletRequest request,
			HttpServletResponse response) throws IOException{

		String debtNo =  request.getParameter("debtNo");
		DebtInfo debtInfo= new DebtInfo();
		if(debtNo==null || debtNo.equals(""))
			debtInfo = (DebtInfo) request.getSession().getAttribute("ratingDebt");
		else
			debtInfo = obligationService.findDebtInfoById(debtNo);
		
		JsonConfig jsonConfig= new JsonConfig();  
		jsonConfig.registerDefaultValueProcessor(Integer.class,  
		    new DefaultValueProcessor(){  
		        public Object getDefaultValue(Class type){  
		            return JSONNull.getInstance();  
		        }  
		    });  
		
		if(debtInfo.getLgd() != null) debtInfo.setLgd(debtInfo.getLgd() * 100);
		Map map = new HashMap();
		map.put("success", true);
		map.put("data", debtInfo);
		
		JSONObject debtJO = JSONObject.fromObject(map,jsonConfig);
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(debtJO);
		////log.info("JSON数据："+debtJO);
	}
	
	//获取某笔债项的详情
	//获取单一债项
	@RequestMapping("/checkMyDebt")
	public String checkMyDebt(HttpServletRequest request,
			HttpServletResponse response) throws IOException{

		String debtNo =  request.getParameter("debtNo");
		DebtInfo debtInfo= new DebtInfo();
		debtInfo = obligationService.findDebtInfoById(debtNo);
		request.getSession().setAttribute("ratingDebt", debtInfo);
		
		return "rating/DebtRating_DebtInfo";
	}
	
	@RequestMapping("/showReportDate")
	public void showReportDate(HttpServletRequest request, 
			HttpServletResponse response)throws IOException{
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		List<Map<String,String>> addTypeList = new ArrayList<Map<String,String>>();
		
		String custId = (String) request.getSession().getAttribute("CustId");
		List<ModelHis> modelList = modelService.findEffectedModelHis();
		List<String> reportDateList = customerService.findReportDate(custId);
		for(String reportDate :reportDateList){
			Map<String, String> addTypeMap = new LinkedHashMap<String, String>();
	    	addTypeMap.put("code", reportDate);
	    	addTypeMap.put("name", reportDate);
	    	addTypeList.add(addTypeMap);  
		}
		JSONArray jo = JSONArray.fromObject(addTypeList);
		PrintWriter out = response.getWriter();
		out.print(jo);
	}
	//客户列表-->客户报告
	@RequestMapping("/showReportHistoryPDList")
	public String showReportHistoryPDList(HttpServletRequest request, 
			HttpServletResponse response){
		
		String custId = request.getParameter("custId");
		
		CustInfo custInfo = customerService.findCustByCustId(custId);
		IndInfo indInfo = customerService.findIndCustByCustId(custId);
		
		if(custInfo != null && indInfo == null){
			request.getSession().removeAttribute("ratingCustId");
			request.getSession().setAttribute("ratingCustId", custId);
			request.getSession().removeAttribute("ratingCustName");
			request.getSession().setAttribute("ratingCustName", custInfo.getCustName());
			request.getSession().removeAttribute("ratingCustType");
			request.getSession().setAttribute("ratingCustType",DataDictionary.getInstance().getNameByCodeAndId("CustType", custInfo.getCustType()));
			request.getSession().removeAttribute("ratingIndustryType");
			request.getSession().setAttribute("ratingIndustryType", DataDictionary.getInstance().getNameByCodeAndId("IndustryType", custInfo.getIndustryType()));
			return "rating/RatingReport_HistoryRating";
		}
		else if(custInfo == null && indInfo != null){
			request.getSession().removeAttribute("ratingCustId");
			request.getSession().setAttribute("ratingCustId", custId);
			request.getSession().removeAttribute("ratingCustName");
			request.getSession().setAttribute("ratingCustName", indInfo.getCustName());
			request.getSession().removeAttribute("ratingCustType");
			request.getSession().setAttribute("ratingCustType", "零售客户");
			request.getSession().removeAttribute("ratingIndIDNo");
			request.getSession().setAttribute("ratingIndIDNo", indInfo.getIdno());
			
			return "rating/RatingReport_IndHistoryRating";
		}
		else return null;
		
	}

	
	//列出该客户的历史评级信息,评级报告（已认定）
	@RequestMapping("/listReportHistoryPD")
	public void listReportHistoryPD(HttpServletRequest request,HttpServletResponse response) throws IOException, ParseException{ 
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		
		//分页
		Integer start = Integer.parseInt(request.getParameter("start"));
		Integer limit = Integer.parseInt(request.getParameter("limit"));
		//评级的客户ID
		String ratingCustId = "";
		if(request.getSession().getAttribute("ratingCustId")!=null)
			ratingCustId = request.getSession().getAttribute("ratingCustId").toString();
		
		/*//test 
		ratingCustId = "111";*/
		//该客户的历史评级信息
		List<PdH> list;
		list = ratingService.findReportHistoryRatingPdH(ratingCustId);
		//分页
		List<PdH> pageList;
		if(list.size()>start+limit)
			pageList = list.subList(start, limit+start); 
		else
			pageList = list.subList(start,list.size());
		
		//将某些字段的code变成name
		for(PdH p : pageList){
			if(p.getConfirmDate()!=null && !("").equals(p.getConfirmDate())){
				String confirmDate = p.getConfirmDate();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");   
                Calendar cd = Calendar.getInstance();   
                cd.setTime(sdf.parse(confirmDate));   
                cd.add(Calendar.YEAR, 1);
                cd.add(Calendar.DATE, -1);//减少一天  
				String endDate = sdf.format(cd.getTime());  
				p.setEndDate(endDate);
			}
			p.setModelId(modelService.findModelHisById(p.getModelId()).getModelName());
			p.setPhaseStat(DataDictionary.getInstance().getNameByCodeAndId("PhaseStat", p.getPhaseStat()));
		}
		
		Map<String, Object> myCustMap = new HashMap<String, Object>(3);
		myCustMap.put("total", list.size());
		myCustMap.put("resultData", pageList);
		JSONObject myCustJO=JSONObject.fromObject(myCustMap);
		out.print(myCustJO);
		
		////log.info("JSON数据："+myCustJO);
	}
	
	//显示评级报告
	@RequestMapping("showRatingReport")
	public String showRatingReport(HttpServletRequest request,HttpServletResponse response) throws IOException, ParseException{
		//log.info("提供打印报表所需的信息项");
		//评级编号
		String serialNo = request.getParameter("serialNo");
		boolean isSpecial = false;// 对公客户手填定量的情况
		boolean isRetail = false; // 零售客户
		//评级报告编号字段：
		String confirmDateNum = "00000000";
		String orgNoNum = "00000";
		String exposureTypeNum = "000";
		String modelNum = "0000";
		String flowNum = "000";
		
		PdH pdh = ratingService.findPDById(serialNo);
		if(pdh == null) return null;
		CustInfo custInfo = customerService.findCustByCustId(pdh.getCustId());
		IndInfo indInfo = customerService.findIndCustByCustId(pdh.getCustId());
		OrgInfo firstOrgInfo = systemService.findOrgById(pdh.getFirstOrgId());
		if(custInfo != null && indInfo == null) isRetail = false;
		else if(custInfo == null && indInfo != null) isRetail = true;
		else return null;
		ModelHis model = modelService.findModelHisById(pdh.getModelId());
		if(model == null) return null;
		
		
		//生成评级报告编号，由于此时评级已经结束，故生成一次即为永久正确的数据。所以若之前已生成，则不用再次生成
		if(pdh.getReportNum() == null || pdh.getReportNum().equals("")){
			if(firstOrgInfo.getBankid() != null && !firstOrgInfo.getBankid().equals(""))orgNoNum = firstOrgInfo.getBankid();
			if(model.getModelVersion() != null )modelNum = model.getModelVersion();
			String exposureType = null;
			if(custInfo != null && custInfo.getExposureType() != null && !custInfo.getExposureType().equals("")){
				exposureType = custInfo.getExposureType();
				
			}
			else if(indInfo != null && indInfo.getExposureType() != null && !indInfo.getExposureType().equals("")){
				exposureType = indInfo.getExposureType();
			}
			if(exposureType != null){
				String exposureTypeCode = DataDictionary.getInstance().getIdNoByCodeAndName("ExposureType", exposureType);
				if(exposureTypeCode != null){
					if(exposureTypeCode.length() == 2){
						exposureTypeNum = exposureTypeCode.substring(1,2)+ "00";
					}
					else if(exposureTypeCode.length() == 4){
						exposureTypeNum = exposureTypeCode.substring(1);
					}
				}
			}
			
		}
		
		if(!isRetail){
			if(pdh.getConfirmDate()!=null && !("").equals(pdh.getConfirmDate())){
				String confirmDate = pdh.getConfirmDate();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");   
	            Calendar cd = Calendar.getInstance();   
	            cd.setTime(sdf.parse(confirmDate));   
	            cd.add(Calendar.YEAR, 1);
	            cd.add(Calendar.DATE, -1);//减少一天  
				String endDate = sdf.format(cd.getTime());  
				pdh.setEndDate(endDate);
				
				if(pdh.getReportNum() == null || pdh.getReportNum().equals("")){
					SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd"); 
					cd = Calendar.getInstance();
					cd.setTime(sdf.parse(confirmDate)); 
		            confirmDateNum = sdf2.format(cd.getTime());
		            
		            int num = ratingService.getConfirmedOrderByConfirmDate(pdh.getSerialNo(), pdh.getConfirmDate());
		            num = num % 1000;//只生成三位流水号
		            if(num / 100 > 0) flowNum = "";
		            else if(num / 10 > 0) flowNum = "0";
		            else flowNum = "00";
		            flowNum += num;
		          //更新评级报告编号
					pdh.setReportNum(confirmDateNum + orgNoNum + exposureTypeNum + modelNum + flowNum);
					ratingService.updatePdH(pdh);
				}
				
	            
			}
			pdh.setFirstOrgId(systemService.findOrgById(pdh.getFirstOrgId()).getOrgname());
			pdh.setFirstUserId(systemService.findUserById(pdh.getFirstUserId()).getUsername());
			pdh.setModelName(modelService.findModelHisById(pdh.getModelId()).getModelName());
			
			List<RatioValue> ratioList = ratingService.findRatioValueBySerialNoAndModelId(pdh.getSerialNo(), pdh.getModelId());
			List<QuaValue> quaList = ratingService.findQuaValueBySerialNoAndModelId(pdh.getSerialNo(), pdh.getModelId());
			List<ModelInfo> modelInfoList = modelService.findModelInfoByModelIdAndDataFlag(pdh.getModelId(), ModelInfo.QUALITY_FACTOR);
			List<PdH> pdList = ratingService.findHistoryRatingPdH(custInfo.getCustId());
			List<DebtInfo> debtList = obligationService.findDebtByCustId(custInfo.getCustId());
			
			if(ratioList.size() > 0 && ratioList.get(0).getId().getReportItemNo().length() >= 12) {
				isSpecial = true;
			}
			
			//找到所有已认定的历史评级
			//如果第一个的状态不是认定的，则remove掉
			if(pdList.size() > 0 ){
				if(!pdList.get(0).getPhaseStat().equals("06"))
					pdList.remove(pdList.get(0));
			}
			//移除第一个后，如果size大于0，则remove掉最新的
			if(pdList.size() > 0){
				pdList.remove(pdh);
			}
			
			custInfo.setInputUserName(systemService.findUserById(custInfo.getInputUserId()).getUsername());
			for(QuaValue qv : quaList){
				for(ModelInfo mi : modelInfoList){
					if(qv.getId().getItemNo().equals(mi.getItemNo()) && qv.getItemValue().equals(mi.getItemValue())){
						qv.setItemDescription(mi.getItemDescribe());
						qv.setDescribe(mi.getDescribe2());
						break;
					}
				}
			}
			
			//债项评级信息放入DebtMap中
			Map<DebtInfo,List<CollateralInfo>> debtMap = new HashMap<DebtInfo,List<CollateralInfo>>();
			for(DebtInfo di : debtList){
				List<DebtCollateral> debtCollateralList = obligationService.findDebtCollateralByDebtNo(di.getDebtNo());
				List<CollateralInfo> collateralList = new ArrayList<CollateralInfo>();
				for(DebtCollateral dc : debtCollateralList){
					collateralList.add(obligationService.findCollateralById(dc.getId().getCollateralId()));
				}
				
				debtMap.put(di, collateralList);
			}
			
			Iterator<PdH> it = pdList.iterator();
			while(it.hasNext()){
				PdH p = it.next();
				if(p.getSerialNo().equals(pdh.getSerialNo())) {
					it.remove();
					continue;
				}
//				p = ratingService.findPDById(serialNo);
				if(p.getConfirmDate()!=null && !("").equals(p.getConfirmDate())){
					if(pdh.getConfirmDate()!=null && !("").equals(pdh.getConfirmDate())){
						if(p.getConfirmDate().compareTo(pdh.getConfirmDate()) >=0){//新于当前评级的条目删除
							it.remove();
							continue;
						}
					}
					String confirmDate = p.getConfirmDate();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");   
	                Calendar cd = Calendar.getInstance();   
	                cd.setTime(sdf.parse(confirmDate));   
	                cd.add(Calendar.YEAR, 1);
	                cd.add(Calendar.DATE, -1);//减少一天  
					String endDate = sdf.format(cd.getTime());  
					p.setEndDate(endDate);
				}
				p.setFirstOrgId(systemService.findOrgById(p.getFirstOrgId()).getOrgname());
				p.setFirstUserId(systemService.findUserById(p.getFirstUserId()).getUsername());
				p.setModelName(modelService.findModelHisById(p.getModelId()).getModelName());
			}

			CustLimit custLimit = riskAppService.findCustLimitByCustId(custInfo.getCustId());
			//custLimit.getFinalLimit()
			
			
			pdh.setSerialNo(pdh.getReportNum());//显示需要
			//评级报告需要展示的信息
			request.getSession().setAttribute("reportPD", pdh);
			request.getSession().setAttribute("reportCustLimit", custLimit);
			request.getSession().setAttribute("reportCustInfo", custInfo);
			request.getSession().setAttribute("isSpecial", isSpecial? 1:0);
			request.getSession().setAttribute("reportRatioList", ratioList);
			request.getSession().setAttribute("reportQuaList", quaList);
			request.getSession().setAttribute("reportPDList", pdList);
			request.getSession().setAttribute("reportDebtMap", debtMap);
			request.getSession().setAttribute("reportDate", CalendarUtil.getCurrentDateStr());	
			
			return "rating/RatingReportData";
		}

		else{//零售客户：
			List<ModelInfo> modelInfoList = modelService.findModelInfoByModelIdAndDataFlag(pdh.getModelId(), ModelInfo.ADJUST_ITEM);
			
			if(pdh.getSecondDate()!=null && !("").equals(pdh.getSecondDate()) && pdh.getReportNum() == null || pdh.getReportNum().equals("")){
				String confirmDate = pdh.getSecondDate();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
	            Calendar cd = Calendar.getInstance();   
	            cd.setTime(sdf.parse(confirmDate)); 
	            confirmDateNum = sdf2.format(cd.getTime());
	            
	            int num = ratingService.getIndConfirmedOrderBySecondDate(pdh.getSerialNo(), pdh.getSecondDate());
	            num = num % 1000;//只生成三位流水号
	            if(num / 100 > 0) flowNum = "";
	            else if(num / 10 > 0) flowNum = "0";
	            else flowNum = "00";
	            flowNum += num;
	            //更新评级报告编号
				pdh.setReportNum(confirmDateNum + orgNoNum + exposureTypeNum + modelNum + flowNum);
				ratingService.updatePdH(pdh);
			}
			
			pdh.setFirstOrgId(systemService.findOrgById(pdh.getFirstOrgId()).getOrgname());
			pdh.setFirstUserId(systemService.findUserById(pdh.getFirstUserId()).getUsername());
			pdh.setSecondOrgId(systemService.findOrgById(pdh.getSecondOrgId()).getOrgname());
			pdh.setSecondUserId(systemService.findUserById(pdh.getSecondUserId()).getUsername());
			pdh.setModelName(model.getModelName());
			pdh.setFirstPdlevel(DataDictionary.getInstance().getNameByCodeAndId("IndSystemResult", pdh.getFirstPdlevel()));
			pdh.setSecondPdlevel(DataDictionary.getInstance().getNameByCodeAndId("IndSystemResult", pdh.getSecondPdlevel()));
			
			List<AdjValue> adjValueList = ratingService.findAdjValueBySerialNoAndModelId(pdh.getSerialNo(), pdh.getModelId());
			if(adjValueList != null){
				for(AdjValue item :adjValueList){
					String itemNo = item.getId().getItemNo();
					for(ModelInfo modelInfo : modelInfoList){
						if(modelInfo.getItemNo().equals(itemNo)){
							item.setItemTitle(modelInfo.getDescribe1());
							request.getSession().setAttribute("reportDate", CalendarUtil.getCurrentDateStr());	
						}
					}
				}
			}

			
			pdh.setSerialNo(pdh.getReportNum());//显示需要
			request.getSession().setAttribute("reportPD", pdh);
			request.getSession().setAttribute("reportCustInfo", indInfo);
			request.getSession().setAttribute("reportAdjustList", adjValueList);
			request.getSession().setAttribute("firstOrgNo", firstOrgInfo.getBankid() == null? "":firstOrgInfo.getBankid());
			
			return "rating/IndRatingReportData";
		}
		
	}
	 
	@RequestMapping("calculateDebtRating")
	public void calculateDebtRating(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String debtNo = request.getParameter("debtNo");
		String debtBalance = request.getParameter("debtBalance");
		String debtQuality = request.getParameter("debtQuality");
		String debtSumString = request.getParameter("debtSum");

		//为抵押品的折扣系数(适用于外币)
		final double foreignIndex = 0.08;
		
		DebtInfo debtInfo= new DebtInfo();
		debtInfo = obligationService.findDebtInfoById(debtNo);
		
		Double exposureValue = 0.0;
		Double debtSum = Double.valueOf(debtSumString);
		exposureValue = Double.valueOf(debtBalance);
		
		double E = exposureValue;
		
		//更新债项余额
		debtInfo.setDebtBalance(exposureValue);
		debtInfo.setDebtSum(debtSum);
		debtInfo.setDebtQuality(debtQuality);
		
		//TODO 确认下多种抵质押品下EAD的计算办法：E * CCF？E是指暴露余额吗？——是
		String ccfString = "0";
		if(debtInfo.getDebtType() != null || !debtInfo.getDebtType().equals("")){
			String debtTypeLevelOne = debtInfo.getDebtType().substring(0, 4);
			ccfString = DataDictionary.getInstance().getNameByCodeAndId("CCFParam", debtTypeLevelOne);
		}
		Double ccfParam = 0.00;
		if(FormatUtil.isDouble(ccfString)) ccfParam = Double.parseDouble(ccfString);
		Double ead = exposureValue + Math.max(0, debtSum - exposureValue) * ccfParam;
		
		//是否为外币
		boolean isForeign;
		String currency = debtInfo.getCurrency();
		if(("01").equals(currency)){
			isForeign = false;
		}else{
			isForeign = true;
		}
		
		//计算LGD,先计算单个，再按权重汇总
		DebtRatingCalculator drc = new DebtRatingCalculator(debtQuality);
		//遍历该债项的所有抵质押品，分别找出各种种类的抵质押品
		List<DebtCollateral> fiancialList = new ArrayList<DebtCollateral>();
		List<DebtCollateral> accountList = new ArrayList<DebtCollateral>();
		List<DebtCollateral> estateList = new ArrayList<DebtCollateral>();
		List<DebtCollateral> otherList = new ArrayList<DebtCollateral>();
		
		List<DebtCollateral> dcList = obligationService.findDebtCollateralByDebtNo(debtNo);
		for(DebtCollateral dc : dcList){
			CollateralInfo col = obligationService.findCollateralById(dc.getId().getCollateralId());
			if(col.getCollateralType().startsWith(DebtRatingCalculator.fiancialCollateral)){
				fiancialList.add(dc);
			}else if (col.getCollateralType().startsWith(DebtRatingCalculator.receivableAccount)){
				accountList.add(dc);
			}else if (col.getCollateralType().startsWith(DebtRatingCalculator.realEstate)){
				estateList.add(dc);
			}else if(col.getCollateralType().startsWith(DebtRatingCalculator.otherCollateral)){
				otherList.add(dc);
			}
		}

		//先算出金融的LGD和所覆盖的金额
		double collateralValue1 = 0.00;
		for(DebtCollateral dc : fiancialList){
			CollateralInfo ci = obligationService.findCollateralById(dc.getId().getCollateralId());
			double value = ci.getNowValue();
			//折扣
			String itemNo = ci.getCollateralType()+"-"+((ci.getPublish() == null || ci.getPublish().equals("")) ? "01":ci.getPublish()) +"-" + ((ci.getYear() == null || ci.getPublish().equals(""))? "01":ci.getYear());
			String discountString = DataDictionary.getInstance().getNameByCodeAndId("DiscountParam", itemNo);
			double discount = 0.0;
			if(FormatUtil.isDouble(discountString)){
				discount = Double.parseDouble(discountString);
			}
			value *= 1 - discount;
			//分摊
			double share = ratingService.getShare(debtNo, E, ci.getCollateralId());
			collateralValue1 += value * share;
		}
		//如果是外币，抵押品价值会有一个折扣系数
		if(isForeign) collateralValue1 = collateralValue1*(1-foreignIndex);
		double lgd1 = drc.calculateLGD(DebtRatingCalculator.fiancialCollateral, exposureValue, collateralValue1);
		
		
		//接下来计算应收账款的
		exposureValue = Math.max(exposureValue - collateralValue1, 0);
		double collateralValue2 = 0.00;
		for(DebtCollateral dc : accountList){
			CollateralInfo ci = obligationService.findCollateralById(dc.getId().getCollateralId());
			double share = ratingService.getShare(debtNo, E, ci.getCollateralId());
			collateralValue2 += ci.getNowValue() * share;
		}
		//如果是外币，抵押品价值会有一个折扣系数
		if(isForeign) collateralValue2 = collateralValue2*(1-foreignIndex);
		double lgd2 = drc.calculateLGD(DebtRatingCalculator.receivableAccount, exposureValue, collateralValue2);
		
		//接下来是房地产
		exposureValue = Math.max(exposureValue - collateralValue2, 0);
		double collateralValue3 = 0.00;
		for(DebtCollateral dc : estateList){
			CollateralInfo ci = obligationService.findCollateralById(dc.getId().getCollateralId());
			double share = ratingService.getShare(debtNo, E, ci.getCollateralId());
			collateralValue3 += ci.getNowValue() * share;
		}
		//如果是外币，抵押品价值会有一个折扣系数
		if(isForeign) collateralValue3 = collateralValue3*(1-foreignIndex);
		double lgd3 = drc.calculateLGD(DebtRatingCalculator.realEstate, exposureValue, collateralValue3);
		
		//最后是其他
		exposureValue = Math.max(exposureValue - collateralValue3, 0);
		double collateralValue4 = 0.00;
		for(DebtCollateral dc : otherList){
			CollateralInfo ci = obligationService.findCollateralById(dc.getId().getCollateralId());
			double share = ratingService.getShare(debtNo, E, ci.getCollateralId());
			collateralValue4 += ci.getNowValue() * share;
		}
		//如果是外币，抵押品价值会有一个折扣系数
		if(isForeign) collateralValue4 = collateralValue4*(1-foreignIndex);
		double lgd4 = drc.calculateLGD(DebtRatingCalculator.otherCollateral, exposureValue, collateralValue4);
		
		//都求完之后，计算其加权平均
		double w1 = Math.min(1, collateralValue1 / E);
		double w2 = Math.max(Math.min(E - collateralValue1, collateralValue2)/E, 0);
		double w3 = Math.max(Math.min(E - collateralValue1 - collateralValue2, collateralValue3)/E, 0);
		double w4 = Math.max(Math.min(E - collateralValue1 - collateralValue2 - collateralValue3, collateralValue4)/E, 0);
		double w5 = Math.max((E - collateralValue1 - collateralValue2 - collateralValue3 - collateralValue4)/E, 0);
		
		
		double lgd = w1 * 0 + w2 *lgd2 + w3 * lgd3 + w4 * lgd4 + w5 * drc.getFinancialLGD();
		
		debtInfo.setLgd(lgd);
		debtInfo.setEad(ead);
//		obligationService.updateDebtInfo(debtInfo);
//		
//		LgdH lgdH = new LgdH();
//		lgdH.setDebtBalance(Double.valueOf(debtBalance));
//		lgdH.setDebtNo(debtNo);
//		lgdH.setLgd(lgd);
//		lgdH.setEad(ead);
//		lgdH.setInputDate(CalendarUtil.getCurrentDateStr());
//		
//		ratingService.insertLGD(lgdH);
		
		//为百分比显示需要
		double lgdValue = debtInfo.getLgd();
		DecimalFormat df = new DecimalFormat("##.0000");
		debtInfo.setLgd(Double.parseDouble(df.format(lgdValue)) * 100);
		
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		Map map = new HashMap();
		map.put("success", true);
		map.put("data", debtInfo);
		JSONObject debtJO = JSONObject.fromObject(map);
		out.print(debtJO);
		
	}

	@RequestMapping("saveDebtRating")
	public void saveDebtRating(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String debtNo = request.getParameter("debtNo");
		String debtBalance = request.getParameter("debtBalance");
		String debtQuality = request.getParameter("debtQuality");
		String debtSumString = request.getParameter("debtSum");

		//为抵押品的折扣系数(适用于外币)
		final double foreignIndex = 0.08;
		
		DebtInfo debtInfo= new DebtInfo();
		debtInfo = obligationService.findDebtInfoById(debtNo);
		
		Double exposureValue = 0.0;
		Double debtSum = Double.valueOf(debtSumString);
		exposureValue = Double.valueOf(debtBalance);
		
		double E = exposureValue;
		
		//更新债项余额
		debtInfo.setDebtBalance(exposureValue);
		debtInfo.setDebtSum(debtSum);
		debtInfo.setDebtQuality(debtQuality);
		
		//TODO 确认下多种抵质押品下EAD的计算办法：E * CCF？E是指暴露余额吗？——是
		String ccfString = "0";
		if(debtInfo.getDebtType() != null || !debtInfo.getDebtType().equals("")){
			String debtTypeLevelOne = debtInfo.getDebtType().substring(0, 4);
			ccfString = DataDictionary.getInstance().getNameByCodeAndId("CCFParam", debtTypeLevelOne);
		}
		Double ccfParam = 0.00;
		if(FormatUtil.isDouble(ccfString)) ccfParam = Double.parseDouble(ccfString);
		Double ead = exposureValue + Math.max(0, debtSum - exposureValue) * ccfParam;
		
		//是否为外币
		boolean isForeign;
		String currency = debtInfo.getCurrency();
		if(("01").equals(currency)){
			isForeign = false;
		}else{
			isForeign = true;
		}
		
		//计算LGD,先计算单个，再按权重汇总
		DebtRatingCalculator drc = new DebtRatingCalculator(debtQuality);
		//遍历该债项的所有抵质押品，分别找出各种种类的抵质押品
		List<DebtCollateral> fiancialList = new ArrayList<DebtCollateral>();
		List<DebtCollateral> accountList = new ArrayList<DebtCollateral>();
		List<DebtCollateral> estateList = new ArrayList<DebtCollateral>();
		List<DebtCollateral> otherList = new ArrayList<DebtCollateral>();
		
		List<DebtCollateral> dcList = obligationService.findDebtCollateralByDebtNo(debtNo);
		for(DebtCollateral dc : dcList){
			CollateralInfo col = obligationService.findCollateralById(dc.getId().getCollateralId());
			if(col.getCollateralType().startsWith(DebtRatingCalculator.fiancialCollateral)){
				fiancialList.add(dc);
			}else if (col.getCollateralType().startsWith(DebtRatingCalculator.receivableAccount)){
				accountList.add(dc);
			}else if (col.getCollateralType().startsWith(DebtRatingCalculator.realEstate)){
				estateList.add(dc);
			}else if(col.getCollateralType().startsWith(DebtRatingCalculator.otherCollateral)){
				otherList.add(dc);
			}
		}

		//先算出金融的LGD和所覆盖的金额
		double collateralValue1 = 0.00;
		for(DebtCollateral dc : fiancialList){
			CollateralInfo ci = obligationService.findCollateralById(dc.getId().getCollateralId());
			double value = ci.getNowValue();
			//折扣
			String itemNo = ci.getCollateralType()+"-"+ci.getPublish() +"-" + ci.getYear();
			String discountString = DataDictionary.getInstance().getNameByCodeAndId("DiscountParam", itemNo);
			double discount = 0.0;
			if(FormatUtil.isDouble(discountString)){
				discount = Double.parseDouble(discountString);
			}
			value *= 1 - discount;
			//分摊
			double share = ratingService.getShare(debtNo, E, ci.getCollateralId());
			collateralValue1 += value * share;
		}
		//如果是外币，抵押品价值会有一个折扣系数
		if(isForeign) collateralValue1 = collateralValue1*(1-foreignIndex);
		double lgd1 = drc.calculateLGD(DebtRatingCalculator.fiancialCollateral, exposureValue, collateralValue1);
		
		
		//接下来计算应收账款的
		exposureValue = Math.max(exposureValue - collateralValue1, 0);
		double collateralValue2 = 0.00;
		for(DebtCollateral dc : accountList){
			CollateralInfo ci = obligationService.findCollateralById(dc.getId().getCollateralId());
			double share = ratingService.getShare(debtNo, E, ci.getCollateralId());
			collateralValue2 += ci.getNowValue() * share;
		}
		//如果是外币，抵押品价值会有一个折扣系数
		if(isForeign) collateralValue2 = collateralValue2*(1-foreignIndex);
		double lgd2 = drc.calculateLGD(DebtRatingCalculator.receivableAccount, exposureValue, collateralValue2);
		
		//接下来是房地产
		exposureValue = Math.max(exposureValue - collateralValue2, 0);
		double collateralValue3 = 0.00;
		for(DebtCollateral dc : estateList){
			CollateralInfo ci = obligationService.findCollateralById(dc.getId().getCollateralId());
			double share = ratingService.getShare(debtNo, E, ci.getCollateralId());
			collateralValue3 += ci.getNowValue() * share;
		}
		//如果是外币，抵押品价值会有一个折扣系数
		if(isForeign) collateralValue3 = collateralValue3*(1-foreignIndex);
		double lgd3 = drc.calculateLGD(DebtRatingCalculator.realEstate, exposureValue, collateralValue3);
		
		//最后是其他
		exposureValue = Math.max(exposureValue - collateralValue3, 0);
		double collateralValue4 = 0.00;
		for(DebtCollateral dc : otherList){
			CollateralInfo ci = obligationService.findCollateralById(dc.getId().getCollateralId());
			double share = ratingService.getShare(debtNo, E, ci.getCollateralId());
			collateralValue4 += ci.getNowValue() * share;
		}
		//如果是外币，抵押品价值会有一个折扣系数
		if(isForeign) collateralValue4 = collateralValue4*(1-foreignIndex);
		double lgd4 = drc.calculateLGD(DebtRatingCalculator.otherCollateral, exposureValue, collateralValue4);
		
		//都求完之后，计算其加权平均
		double w1 = Math.min(1, collateralValue1 / E);
		double w2 = Math.max(Math.min(E - collateralValue1, collateralValue2)/E, 0);
		double w3 = Math.max(Math.min(E - collateralValue1 - collateralValue2, collateralValue3)/E, 0);
		double w4 = Math.max(Math.min(E - collateralValue1 - collateralValue2 - collateralValue3, collateralValue4)/E, 0);
		double w5 = Math.max((E - collateralValue1 - collateralValue2 - collateralValue3 - collateralValue4)/E, 0);
		
		
		double lgd = w1 * 0 + w2 *lgd2 + w3 * lgd3 + w4 * lgd4 + w5 * drc.getFinancialLGD();
		
		debtInfo.setLgd(lgd);
		debtInfo.setEad(ead);
		debtInfo.setDebtRatingDate(CalendarUtil.getCurrentDateStr());
		obligationService.updateDebtInfo(debtInfo);
		
		LgdH lgdH = new LgdH();
		lgdH.setDebtBalance(Double.valueOf(debtBalance));
		lgdH.setDebtNo(debtNo);
		lgdH.setLgd(lgd);
		lgdH.setEad(ead);
		lgdH.setInputDate(CalendarUtil.getCurrentDateStr());
		
		ratingService.insertLGD(lgdH);
		
		//为百分比显示需要
		double lgdValue = debtInfo.getLgd();
		DecimalFormat df = new DecimalFormat("##.0000");
		debtInfo.setLgd(Double.parseDouble(df.format(lgdValue)) * 100);
		
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		Map map = new HashMap();
		map.put("success", true);
		map.put("data", debtInfo);
		JSONObject debtJO = JSONObject.fromObject(map);
		out.print(debtJO);
	}
	
	
	@RequestMapping("showPDDetail")
	public String showPDDetail(HttpServletRequest request,
			HttpServletResponse response){
		String serialNo = request.getParameter("serialNo");
		PdH pdh = new PdH();
		pdh = ratingService.findPDById(serialNo);
		
		request.getSession().removeAttribute("ratingPD");
		request.getSession().setAttribute("ratingPD",pdh );
		
		request.getSession().removeAttribute("pdId");
		request.getSession().setAttribute("pdId", pdh.getSerialNo());
		
		String usedModelId = pdh.getModelId();
		request.getSession().removeAttribute("usedModelId");
		request.getSession().setAttribute("usedModelId", usedModelId);

		request.getSession().removeAttribute("reportDate");
		request.getSession().setAttribute("reportDate", pdh.getReportDate());
		
		//Object indCustId = request.getSession().getAttribute("indCustId");
		Object custId = request.getSession().getAttribute("ratingCustId");
		if(custId!=null && !custId.toString().equals("")){
			IndInfo indInfo = customerService.findIndCustByCustId(custId.toString());
			if(indInfo!=null){
				request.getSession().removeAttribute("exposureType");
				request.getSession().setAttribute("exposureType", indInfo.getExposureType());
			}
		}else if (custId!=null){
			CustInfo custInfo = customerService.findCustByCustId(custId.toString());
			if(custInfo != null){
				request.getSession().removeAttribute("exposureType");
				request.getSession().setAttribute("exposureType", custInfo.getExposureType());
			}	
		}else{
			CustInfo custInfo = (CustInfo) request.getSession().getAttribute("custInfo");
			if(custInfo != null){
				request.getSession().removeAttribute("exposureType");
				request.getSession().setAttribute("exposureType", custInfo.getExposureType());
			}
			request.getSession().removeAttribute("ratingCustId");
			request.getSession().setAttribute("ratingCustId", custInfo.getCustId());
		}
		
		

		//标记刷新的字段
		//request.getSession().removeAttribute("resultFlag");
		//request.getSession().setAttribute("resultFlag", "0");

		String modelName = modelService.findModelHisById(usedModelId).getModelName();
		request.getSession().removeAttribute("modelName");
		request.getSession().setAttribute("modelName", modelName);

		ModelHis model = modelService.findModelHisById(usedModelId);
		//如果是零售客户
		if(model.getModelKind1().equals("04")){
			return "rating/CustomerRating_IndRatingProcess";
		}else{
			String kind2 = modelService.findModelHisById(usedModelId).getModelKind2();
			if(kind2.equals("0103") || kind2.equals("0105") || kind2.equals("0302"))
				return "rating/CustomerRating_RatingSpecialProcess";
			else return "rating/CustomerRating_RatingProcess";
		}
		
	}
	
	//列出评级模板详情
	@RequestMapping("/listModelItems")
	public void listModelItems(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
	
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		
		String serialNo = request.getSession().getAttribute("pdId").toString();
		String modelId = request.getSession().getAttribute("usedModelId").toString();
		String custId = request.getSession().getAttribute("ratingCustId").toString();
		List<ModelInfo> itemList = new ArrayList<ModelInfo>();
		//String modelId = request.getSession().getAttribute("modelId").toString();
		String dataFlag = request.getParameter("dataFlag");
		
		 
		itemList = modelService.findModelInfoByModelIdAndDataFlag(modelId,dataFlag.substring(0, 1)); //解释：特殊的定量请求，该参数定义为12
		ModelHis modelHis = modelService.findModelHisById(modelId);
		String kind2 = modelHis.getModelKind2();
		boolean isSpecial = false;//定量需手工填写
		if(kind2.equals("0103") || kind2.equals("0105") || kind2.equals("0302")) isSpecial = true;
		
		//若为Qua，其实和Adjustment处理逻辑是一样的
		if(dataFlag.equals("2") ){
			List<QuaValue> quaValueList = ratingService.findQuaValueBySerialNoAndModelId(serialNo, modelId);
			//为结果附加checkSelect
			for(ModelInfo modelInfo : itemList){
				for(QuaValue quaValue : quaValueList){
					if(modelInfo.getItemNo().equals(quaValue.getId().getItemNo()) && modelInfo.getItemValue().equals(quaValue.getItemValue())){
						modelInfo.setCheckSelect(true);
						//log.info("此项为选择的项 "+modelInfo.getDescribe1()+modelInfo.getItemValue());
					}
				}
			}
		}
		//若为Adjustment
		else if(dataFlag.equals("3")){
			//log.info("此次修改的是调整项");
			List<AdjValue> adjValueList = ratingService.findAdjValueBySerialNoAndModelId(serialNo, modelId);
			//为结果附加checkSelect
			for(ModelInfo modelInfo : itemList){
				for(AdjValue adjValue : adjValueList){
					if(modelInfo.getItemNo().equals(adjValue.getId().getItemNo()) 
							&& modelInfo.getItemDescribe().equals(adjValue.getItemDescribe())
							&& modelInfo.getItemValue().equals(adjValue.getItemValue())){
						modelInfo.setCheckSelect(true);
						//log.info("此项为选择的项 "+modelInfo.getDescribe1()+modelInfo.getItemValue());
					}
				}
			}
		}
		//定量因素
		else if(dataFlag.equals("1") && !isSpecial){
			//log.info("此次修改的是定量因素");
			//List<RatioValue> ratioValueList = ratingService.findRatioValueBySerialNoAndModelId(serialNo, modelId);
			List<ModelInfo> ratioList = new ArrayList<ModelInfo>();
			List<RatioValue> ratioValueList = new ArrayList<RatioValue>();
			
			//取得该客户最近一期的年报数据
			String ratingCustId = request.getSession().getAttribute("ratingCustId").toString();
			String reportDate = request.getSession().getAttribute("reportDate").toString();
			ReportList reportList = customerService.findReportByTime(ratingCustId,reportDate);
			
//			int i=0;
//			ReportList lastOneYearReport = null;
//			String lastOneDate = "";
//			for(Object date : map.keySet()){
//				i++;
//				if(lastOneYearReport == null){
//					lastOneYearReport = (ReportList) map.get(date);
//					lastOneDate = date.toString();
//					if(lastOneYearReport != null)
//						break;
//				}
//			}
			//判断客户类型
			int custType = 0; //此处规定：1-企业法人；2-事业单位；3-金融同业；4-零售客户；5-小企业法人
			String reportNo = "0105";
			String reportType = reportList.getReportType();
			CustInfo custInfo = customerService.findCustByCustId(ratingCustId);
			if("01".equals(custInfo.getCustType()) && ("02".equals(reportType))){//小企业法人
				custType = 5;
				reportNo = "0505";
			}
			if(custInfo.getCustType().equals("02")){
				custType = 2;
				reportNo = "0205";
			}
			else if(custInfo.getCustType().equals("03")){
				custType = 3;
				reportNo = "0303";
			}
			
			
			Map<String,Double> map = new HashMap<String,Double>();
			List<ReportData> lastOneFIList = customerService.findRecentReportData(reportList,reportNo);
			//转化为map形式，key为定量因素的itemNo，value为定量因素的值
			for(ReportData rd : lastOneFIList){
				if(rd.getItemValue()!=null)
					map.put(rd.getReportItemNo(),rd.getItemValue());
				else
					map.put(rd.getReportItemNo(),null);//若没有该指标，则ratio中的得分为0（见下方代码的处理逻辑）；
			}
			//log.info("财务指标数据："+map.toString());
			
			//专门处理“批发零售”打分卡的情况：主营业务收入增长率（FR069 || SFR069）使用三年均值！
			if(modelId != null && modelHis != null && modelHis.getModelName() != null && (modelId.equals("ff808081360fc9af01360fd237860028") || modelHis.getModelName().contains("批发零售"))){
				List<ReportData> previousOneFIList = customerService.findPreviousYearReportData(reportList);
				if(previousOneFIList != null && previousOneFIList.size() > 0){
					double lastRatio = 0.0;
					double previousRatio = 0.0;
					for(ReportData item : previousOneFIList){
						if(item.getReportItemNo().contains("FR069")) {
							previousRatio = (item.getItemValue() == null? 0.0:item.getItemValue());
							if(reportNo.equals("0105")) {
								if(map.get("FR069") != null)lastRatio = map.get("FR069").doubleValue();
								map.put("FR069", (lastRatio + previousRatio) / 2);
							}
							else if(reportNo.equals("0505")){
								if(map.get("SFR069") != null)lastRatio = map.get("SFR069").doubleValue();
								map.put("SFR069", (lastRatio + previousRatio) / 2);
							}
						}
					}
				}
			}
			
			//去map中看数值，判断其得分，将得分和权重写入数据库，同时把需要显示的id写成name
			//表示现在遍历到的定量因素
			
			//表示该定量因素是否开始是下一个
			Boolean isEnd = false;
			//表示当前ItemList进行到的项
			int count = 0;
			String beginItemNo = "";
			if(itemList.size() > 0 ){
				beginItemNo = itemList.get(0).getItemNo();
				if(custType == 5){
					//解释：从modelInfo中取得的ItemNo是企业法人与小企业法人共用的编号，当客户是小企时，需要将itemNo前加‘S’
					beginItemNo = "S" + beginItemNo;
				}
			}
			//表示该定量因素是否在区间中
			Boolean flag = false;
			for(ModelInfo modelInfo : itemList){
			
				ModelInfo lastModelInfo = null;
				if(count > 0)
					lastModelInfo = itemList.get(count-1);


				String mappingItemNo = modelInfo.getItemNo();
				if(custType == 5){
					mappingItemNo = "S" + modelInfo.getItemNo();
				}
				
				//先清空该serialNo和modelId下的数据，每次重新生成定量数据的值，执行的是saveOrUpdate方法批量插入
				//模型里面的因素在财务指标表中存在
				
				//表示还是当前的定量因素
				if(beginItemNo.equals(mappingItemNo)){	
					isEnd = false;
				}else{
					isEnd = true;
					beginItemNo = mappingItemNo;
				}
				
				
				
				//log.info("ItemNo: "+mappingItemNo + "是否在Map中存在"+map.containsKey(mappingItemNo));
				Double value = 0.0;
				if(map.get(mappingItemNo) != null) value = (Double)map.get(mappingItemNo);
				
				if(map.containsKey(mappingItemNo)){
					//log.info("数据中存在此ItemNo: "+mappingItemNo);
					//log.info("该项值为:"+value);
					//判断是否处于这个区间，则最终显示的列表中加入此modelInfo，并将该项生成的ratioValue写入db
					//区间，形如(10,20)的形式，进行解析，取出这两个数值，看定量因素值是否在这段区间
					String interval = modelInfo.getItemDescribe();
					//log.info("区间: "+interval);
					StringTokenizer st = new StringTokenizer(interval,"(),");
					String[] data = new String[2];
					int j = 0;
					while(st.hasMoreTokens()){
						String s = st.nextToken();
						//log.info(s);
						data[j] = s.trim();
						j++;
					}
					Double first = Double.valueOf(data[0]);
					Double second = Double.valueOf(data[1]);
					
					//如果此定量因素结束了，并且还是么米有找到在区间中的项则，取上一个modelInfo，并将其value置为:指标大于零认为上越界=100；指标小于零认为下越界=0；值为空=根据原则判断
					if(isEnd  && count > 0){			
						if(!flag){
							String lastMappingItemNo = lastModelInfo.getItemNo();
							if(custType == 5){
								lastMappingItemNo = "S" + lastModelInfo.getItemNo();
							}
							
//							lastModelInfo.setItemValue(0.0);
//							Double itemValue = lastModelInfo.getItemValue();
//							Double reportItemValue = (map.get(lastMappingItemNo) != null? (Double)map.get(lastMappingItemNo):0.0);
							Double reportItemValue = 0.0;//财务指标值
							if(map.get(lastMappingItemNo) != null) reportItemValue = (Double)map.get(lastMappingItemNo);
							lastModelInfo.setItemValue(reportItemValue);  
							lastModelInfo.setReportItemValue(value);
							lastModelInfo.setDescribe2(ReportItemInit.getInstance().getReportItem().get(lastMappingItemNo));
							ratioList.add(lastModelInfo);
							RatioValue rv = new RatioValue();
							RatioValueId id = new RatioValueId();
							id.setModelId(modelId);
							id.setSerialNo(serialNo);
							id.setReportItemNo(lastMappingItemNo);
							rv.setId(id);
							//report_model标注了财务指标为空时的定量得分原则，根据该原则确定该项得分。 当前DB中使用0-0.0/ 1-100.0 ,若映射原则修改，请修改下行代码
							if(map.get(lastMappingItemNo) == null)rv.setItemValue(ReportModelInit.getInstance().getModelValueFlagMap().get(lastMappingItemNo).equals("0")? 0.0 : 100.0);
							//否则为越界情况：
							else{
								if(value > 0) rv.setItemValue(100.0);
								else rv.setItemValue(0.0);
							}
							rv.setReportItemValue(reportItemValue);
							rv.setItemWeight(lastModelInfo.getItemWeight());
							ratioValueList.add(rv);		
							}
						flag = false;
					}
					
					//在此区间内，构造数据，加入ratioList和ratioValueList中
					if((value >= first && value < second) || (value <=first && value > second)){
						flag = true;
						Double itemValue = modelInfo.getItemValue();
						Double reportItemValue = 0.0;
						if(map.get(mappingItemNo) != null) reportItemValue = (Double)map.get(mappingItemNo);
						else itemValue = 0.0;
						modelInfo.setItemValue(reportItemValue);
						modelInfo.setDescribe2(ReportItemInit.getInstance().getReportItem().get(mappingItemNo));
						modelInfo.setReportItemValue(value);
						ratioList.add(modelInfo);
						RatioValue rv = new RatioValue();
						RatioValueId id = new RatioValueId();
						id.setModelId(modelId);
						id.setSerialNo(serialNo);
						id.setReportItemNo(mappingItemNo);
						rv.setId(id);
						rv.setItemValue(itemValue);
						rv.setReportItemValue(reportItemValue);
						rv.setItemWeight(modelInfo.getItemWeight());
						ratioValueList.add(rv);			
					}else{
						//flag = false;
					}					
				}
				//以后可能要处理
				else{
					
				}
				count++;

				isEnd = false;
			}
			//log.info(itemList.toString());
			itemList = ratioList;
			//log.info(itemList.toString());
			ratingService.insertRatioValueList(ratioValueList);
		}
		//定量因素：手填选项（使用的是定性模板）
		else if(dataFlag.equals("12")){
			List<RatioValue> ratioValueList = ratingService.findRatioValueBySerialNoAndModelId(serialNo, modelId);
			//为结果附加checkSelect
			for(ModelInfo modelInfo : itemList){
				for(RatioValue ratioValue : ratioValueList){
					if(modelInfo.getItemNo().equals(ratioValue.getId().getReportItemNo()) && modelInfo.getItemValue().equals(ratioValue.getItemValue())){
						modelInfo.setCheckSelect(true);
						//log.info("此项为选择的项 "+modelInfo.getDescribe1()+modelInfo.getItemValue());
					}
				}
			}
		}
		
		
		
		
//		//构造定量因素数据结构
//		if(dataFlag.equals(ModelInfo.QUANTITY_FACTOR)){
//			//利用两层map，第一层存大类，第二层存该大类下的因素，用map来存储此结构
//			Map<String,Map<String,ModelInfo>> map = new HashMap<String,Map<String,ModelInfo>>();
//			for(ModelInfo modelInfo : itemList){
//				//map中存在该大类，将因素加入此大类中
//				if(map.containsKey(modelInfo.getDescribe1())){
//					map.get(modelInfo.getDescribe1()).put(modelInfo.getItemNo(), modelInfo);
//				}else{
//					Map<String,ModelInfo> subMap = new HashMap<String,ModelInfo>();
//					subMap.put(modelInfo.getItemNo(), modelInfo);
//					map.put(modelInfo.getDescribe1(), subMap);
//				}
//			}
//		}
//		//构造定性因素数据结构
//		else if(dataFlag.equals(ModelInfo.QUALITY_FACTOR)){
//			Map<String,Map<String,Map<String,ModelInfo>>> map = new HashMap<String,Map<String,Map<String,ModelInfo>>>();
//			
//		}else if(dataFlag.equals(ModelInfo.ADJUST_ITEM)){
//			
//			
//		}else{
//			//log.info("不存在该dataFlag。(1.定量 2.定性 3调整项)");
//		}
				
		Map<String, Object> myCustMap = new HashMap<String, Object>(3);
		myCustMap.put("total", itemList.size());
		myCustMap.put("resultData", itemList);
		JSONObject myCustJO=JSONObject.fromObject(myCustMap);
		//log.info("JSON Data: "+myCustMap);
		out.print(myCustJO);
	}	
	
	@RequestMapping("/addQuaValue")
	public void addQuaValue(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		//pdh的serialNo和modelId，用来测试
		String serialNo = request.getSession().getAttribute("pdId").toString();
		String modelId = request.getSession().getAttribute("usedModelId").toString();
		String custId = request.getSession().getAttribute("ratingCustId").toString();
		String data = request.getParameter("newRecord");
		JSONArray jsonArray = JSONArray.fromObject(data);  
		//log.info("data: "+data);
		
		List<QuaValue> listOfQua = new ArrayList<QuaValue>(); 
		List<RatioValue> listOfRatio = new ArrayList<RatioValue>();
		boolean isRatio = false;

    	//此处需判断当前请求是否为特殊打分卡（手选而不是根据财报数值）的定量页面发送的请求
	    ModelInfo mi0 = (ModelInfo) JSONObject.toBean(jsonArray.getJSONObject(0),ModelInfo.class);  
	    mi0 = modelService.findModelInfoById(mi0.getSerialNo());
	    if(mi0.getDataFlag().equals("1")) isRatio = true;
	    
	    if(isRatio){
	    	for ( int i = 0 ; i<jsonArray.size(); i++){            
			    JSONObject jsonObject = jsonArray.getJSONObject(i);  
			    ModelInfo vo = (ModelInfo) JSONObject.toBean(jsonObject,ModelInfo.class);  
			    Boolean flag = vo.getCheckSelect();
			    vo = modelService.findModelInfoById(vo.getSerialNo());
			    vo.setCheckSelect(flag);
			    //log.info("modelInfo: "+vo);
			    
			  //如果checkSelect为真时写入数据库
			    if(vo.getCheckSelect()){
			    	RatioValueId id = new RatioValueId(serialNo, modelId, vo.getItemNo());
			    	RatioValue rv = ratingService.findRatioValueByRatioValueId(id);
			    	//如果数据库存在此reportItemNo的数据，则进行更新
			    	if(rv !=null){
			    		rv.setItemValue(vo.getItemValue());
			    		listOfRatio.add(rv);
			    	}
			    	else{
			    		rv = new RatioValue(id);
			    		rv.setItemValue(vo.getItemValue());
			    		rv.setItemWeight(vo.getItemWeight());
			    		rv.setReportItemValue(0.0);
			    		listOfRatio.add(rv);
			    	}
			    }
	    	}
	    	//需要对进行重复性检查
	    	
	    	List<RatioValue> ratioList = new ArrayList<RatioValue>();
	    	for(RatioValue ratio : listOfRatio){
	    		ratioList.add(ratio);
	    	}
	    	
	    	for(int i=0; i<listOfRatio.size(); i++){
	    		for(int j=0; j<listOfQua.size(); j++){
	    			if(i<j && listOfRatio.get(i).getId().equals(listOfRatio.get(j).getId())){
	    				ratioList.remove(listOfRatio.get(i));
	    			}
	    		}
	    	}
	    	
	    	ratingService.insertRatioValueList(ratioList);
    	}
	    
	    
	    else{
	    	for ( int i = 0 ; i<jsonArray.size(); i++){            
		    JSONObject jsonObject = jsonArray.getJSONObject(i);  
		    ModelInfo vo = (ModelInfo) JSONObject.toBean(jsonObject,ModelInfo.class);  
		    Boolean flag = vo.getCheckSelect();
		    vo = modelService.findModelInfoById(vo.getSerialNo());
		    vo.setCheckSelect(flag);
		    //log.info("modelInfo: "+vo);
		    
		    
		    
		    //如果checkSelect为真时写入数据库
		    if(vo.getCheckSelect()){
		    	
		    	//如果数据库存在此itemNo的数据，则进行更新
		    	if(ratingService.findQuaValueBySerialNoModelIdAndItemNo(serialNo, modelId,vo.getItemNo())!=null){
		    		QuaValue qv = ratingService.findQuaValueBySerialNoModelIdAndItemNo(serialNo, modelId,vo.getItemNo());
		    		//ratingService.deleteQuaValue(qv);
		    		qv.setItemValue(vo.getItemValue());
		    		listOfQua.add(qv);
		    		
		    	}
		    	// 不存在则插入
		    	else{
		    		QuaValueId id = new QuaValueId();
				    id.setItemNo(vo.getItemNo());
				    id.setModelId(vo.getModelId());
				    id.setSerialNo(serialNo);
				    QuaValue qv = new QuaValue();
				    qv.setId(id);
				    qv.setItemValue(vo.getItemValue());
				    qv.setItemWeight(vo.getItemWeight());
				    listOfQua.add(qv);
		    		}
		    	}          
	    	}   
	    	
	    	//需要对Qua进行重复性检查
	    	
	    	List<QuaValue> quaList = new ArrayList<QuaValue>();
	    	for(QuaValue qua : listOfQua){
	    		quaList.add(qua);
	    	}
	    	
	    	for(int i=0; i<listOfQua.size(); i++){
	    		for(int j=0; j<listOfQua.size(); j++){
	    			if(i<j && listOfQua.get(i).getId().equals(listOfQua.get(j).getId())){
	    				quaList.remove(listOfQua.get(i));
	    			}
	    		}
	    	}
	    	
	    	ratingService.insertQuaValueList(quaList);
	    }
		response.getWriter().print("{success:true}");
		
	}
	
	@RequestMapping("/addAdjValue")
	public void addAdjValue(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		//pdh的serialNo和modelId，用来测试
		String serialNo = request.getSession().getAttribute("pdId").toString();
		String modelId = request.getSession().getAttribute("usedModelId").toString();
		String custId = request.getSession().getAttribute("ratingCustId").toString();
		String data = request.getParameter("newRecord");
		JSONArray jsonArray = JSONArray.fromObject(data);  
		//log.info("data: "+data);
		
		List<AdjValue> list = new ArrayList<AdjValue>();  
		for ( int i = 0 ; i<jsonArray.size(); i++){            
		    JSONObject jsonObject = jsonArray.getJSONObject(i);  
		    ModelInfo vo = (ModelInfo) JSONObject.toBean(jsonObject,ModelInfo.class);  
		    Boolean flag = vo.getCheckSelect();
		    vo = modelService.findModelInfoById(vo.getSerialNo());
		    vo.setCheckSelect(flag);
		    //log.info("modelInfo: "+vo);
		    
		    //如果checkSelect为真时写入数据库
		    if(vo.getCheckSelect()){
		    	//如果数据库存在此itemNo的数据，则进行更新
		    	if(ratingService.findAdjValueBySerialNoModelIdAndItemNo(serialNo, modelId,vo.getItemNo())!=null){
		    		AdjValue adj = ratingService.findAdjValueBySerialNoModelIdAndItemNo(serialNo, modelId,vo.getItemNo());
		    		//ratingService.deleteQuaValue(qv);
		    		adj.setItemValue(vo.getItemValue());
		    		adj.setItemDescribe(vo.getItemDescribe());
		    		list.add(adj);
		    		
		    	}
		    	// 不存在则插入
		    	else{
		    		AdjValueId id = new AdjValueId();
				    id.setItemNo(vo.getItemNo());
				    id.setModelId(vo.getModelId());
				    id.setSerialNo(serialNo);
				    AdjValue adj = new AdjValue();
				    adj.setId(id);
				    adj.setItemValue(vo.getItemValue());
				    adj.setItemWeight(vo.getItemWeight());
				    adj.setItemDescribe(vo.getItemDescribe());
				   // adj.setItemSelect(true);
				    list.add(adj);
		    	}
		    }          

		}  
		
		//需要对进行重复性检查
    	
    	List<AdjValue> adjList = new ArrayList<AdjValue>();
    	for(AdjValue adj : list){
    		adjList.add(adj);
    	}
    	
    	for(int i=0; i<list.size(); i++){
    		for(int j=0; j<list.size(); j++){
    			if(i<j && list.get(i).getId().equals(list.get(j).getId())){
    				adjList.remove(list.get(i));
    			}
    		}
    	}
	    
	    ratingService.insertAdjValueList(adjList);
	    
	    request.getSession().removeAttribute("resultFlag");
	    request.getSession().setAttribute("resultFlag", "0");
		
		response.getWriter().print("{success:true}");
		
	}
	
	//获得评级结果
	@RequestMapping("/getRatingResult")
	public void getRatingResult(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String serialNo = request.getSession().getAttribute("pdId").toString();
		String modelId = request.getSession().getAttribute("usedModelId").toString();
		String custId = request.getSession().getAttribute("ratingCustId").toString();
		
		//定性，调整项，定量总得分，总得分
		Double quaValue = 0.0;
		Double adjValue = 0.0;
		Double ratioValue = 0.0;
		Double sum = 0.0;
		
		List<QuaValue> quaList = ratingService.findQuaValueBySerialNoAndModelId(serialNo, modelId);
		List<AdjValue> adjList = ratingService.findAdjValueBySerialNoAndModelId(serialNo, modelId);
		List<RatioValue> ratioList = ratingService.findRatioValueBySerialNoAndModelId(serialNo, modelId);
		
		if(quaList.size()>0){
			for(QuaValue qv : quaList){
				//log.info("小项得分："+qv.getItemValue() * qv.getItemWeight() / 100 / 0.6+" value: "+qv.getItemValue() +" weight: "+qv.getItemWeight());
				quaValue += qv.getItemValue() * qv.getItemWeight() / 100; 
			}
		}	
		if(adjList.size()>0){
			for(AdjValue adj : adjList){
				adjValue += adj.getItemValue();
			}
		}
		if(ratioList.size()>0){
			for(RatioValue ratio : ratioList){
				ratioValue += ratio.getItemValue() * ratio.getItemWeight() / 100;
				//log.info("ratio item:"+ReportItemInit.getInstance().getReportItem().get(ratio.getId().getReportItemNo())
				//		+" ration item value: "+ratio.getReportItemValue()+" ratio value: "+ratio.getItemValue()+
				//" ratio weight:"+ratio.getItemWeight()+" value:" +ratio.getItemValue() * ratio.getItemWeight() / 100);
			}
		}
		
		sum = ratioValue + quaValue + adjValue;

		List<ModelLevel> levelList = modelService.findModelLevelByModelId(modelId);
		//delta表示sum - modelScore
		Double delta = 0.0;
		Double minDelta = 50.0;
		//系统评级结果，例如为AAA
		ModelLevel pdLevel = new ModelLevel();
		//获取该分数对应的PDLevel
		for(ModelLevel level : levelList){
			//首先sum-modelScore>0，并且取delta最小的，才是他对应的level
			delta = sum - level.getModelScore();
			if(delta > 0 && delta < minDelta){
				minDelta = delta;
				pdLevel = level;
			}
		}
		
		Double pdValue = 0.0;
		//得到系统评级结果，取其对应的PD值
		MainscaleHis mainScale = modelService.findMainscaleByState(MainscaleHis.EFFECTED);
		List<MainscaleInfo> mainScaleInfoList = modelService.findMainscaleInfoByMainscaleId(mainScale.getMainScaleId());
		for(MainscaleInfo info : mainScaleInfoList){
			if(info.getPdlevel().equals(pdLevel.getPdlevel())){
				pdValue = info.getPdvalue();
			}
		}
		
		//log.info("定量总得分： "+ratioValue + " 定性总得分： "+quaValue + " 调整项总得分: "
		//		+adjValue + " 总得分: "+sum+" 系统评级: "+pdLevel.getPdlevel() + " PD值： "+pdValue);
		
		String pdId = request.getSession().getAttribute("pdId").toString();
		
		//如果是零售客户，设置其准入分数线和准入，拒绝情况
		ModelHis model = modelService.findModelHisById(modelId);
		String indBorderLine = "";
		String indSystemResult = "";
		if(model != null){
			String modelName = model.getModelName();
			
			List<CodeLib> borderLineList = ParamModelInit.getInstance().getAccessLine();
			
			for(CodeLib codeLib : borderLineList){
				if(modelName.contains(codeLib.getId().getItemNo())){
					indBorderLine = codeLib.getItemName();
					if(sum > Double.parseDouble(indBorderLine)){
						indSystemResult = "01";
					}else{
						indSystemResult = "02";
					}
				}
			}	
		}
		
		
		if(pdId==null){
			PdH pdh = new PdH();
			pdh.setCustId(custId);
			pdh.setModelId(modelId);
			pdh.setQualitativeValue(quaValue);
			pdh.setRatioValue(ratioValue);
			pdh.setAdjustValue(adjValue);
			pdh.setTotalValue(quaValue+ratioValue+adjValue);
			pdh.setSystemPdlevel(pdLevel.getPdlevel());
			pdh.setSystemPdvalue(pdValue);	
			pdh.setSystemDate(CalendarUtil.getCurrentDateStr());
			pdh.setIndBorderLine(indBorderLine);
			pdh.setIndSystemResult(indSystemResult);
			pdh.setPhaseStat("01");
			ratingService.insertPdH(pdh);
		}else{
			PdH ratingPD = ratingService.findPDById(pdId);
			if(ratingPD.getCustId() == null || "".equals(ratingPD.getCustId()))ratingPD.setCustId(custId);
			if(ratingPD.getModelId() == null || "".equals(ratingPD.getModelId()))ratingPD.setModelId(modelId);
			ratingPD.setQualitativeValue(quaValue);
			ratingPD.setRatioValue(ratioValue);
			ratingPD.setAdjustValue(adjValue);
			ratingPD.setTotalValue(quaValue+ratioValue+adjValue);
			ratingPD.setSystemPdlevel(pdLevel.getPdlevel());
			ratingPD.setSystemPdvalue(pdValue);
			ratingPD.setIndBorderLine(indBorderLine);
			ratingPD.setIndSystemResult(indSystemResult);
			ratingPD.setSystemDate(CalendarUtil.getCurrentDateStr());
			if(ratingPD.getPhaseStat().equals("00"))
				ratingPD.setPhaseStat("01");
			ratingService.updatePdH(ratingPD);
		}	
		
		PdH pdH = new PdH();	
		pdH = ratingService.findPDById(pdId);
		pdH.setTotalValue(pdH.getAdjustValue()+pdH.getQualitativeValue()+pdH.getRatioValue());
		
		String phaseStat = pdH.getPhaseStat();
		UserInfo user = (UserInfo) request.getSession().getAttribute("logonUser");
		String accessURL = request.getSession().getAttribute("accessURL").toString();
		if(accessURL!=null && accessURL.contains("FirstPD") && pdH.getFirstUserId()==null){
				pdH.setFirstUser(user.getUsername());
		}
		if(accessURL!=null && accessURL.contains("FirstVerifyPD") && pdH.getFirstVerifyUserId()==null){
			pdH.setFirstVerifyUser(user.getUsername());
		}	
		if(accessURL!=null && accessURL.contains("SecondPD") && pdH.getSecondUserId()==null){
			pdH.setSecondUser(user.getUsername());
		}
		if(accessURL!=null && accessURL.contains("ConfirmPD") && pdH.getConfirmUserId()==null){
			pdH.setConfirmUser(user.getUsername());
		}
		
		if(pdH.getFirstUserId()!=null){
			if(systemService.findUserById(pdH.getFirstUserId())!= null)
				pdH.setFirstUser(systemService.findUserById(pdH.getFirstUserId()).getUsername());
			else
				pdH.setFirstUser("(已删除用户)");
		}
		
		if(pdH.getFirstVerifyUserId()!=null){
			if(systemService.findUserById(pdH.getFirstVerifyUserId())!= null)
				pdH.setFirstVerifyUser(systemService.findUserById(pdH.getFirstVerifyUserId()).getUsername());
			else
				pdH.setFirstVerifyUser("(已删除用户)");
		}
		
		if(pdH.getSecondUserId()!=null){
			if(systemService.findUserById(pdH.getSecondUserId())!= null)
				pdH.setSecondUser(systemService.findUserById(pdH.getSecondUserId()).getUsername());
			else
				pdH.setSecondUser("(已删除用户)");
		}
		
		if(pdH.getConfirmUserId()!=null){
			if(systemService.findUserById(pdH.getConfirmUserId()) != null) 
				pdH.setConfirmUser(systemService.findUserById(pdH.getConfirmUserId()).getUsername());
			else
				pdH.setConfirmUser("(已删除用户)");
		}
		
		Map map = new HashMap();
		map.put("success", true);
		map.put("data", pdH);
		
		JsonConfig jsonConfig= new JsonConfig();  
		jsonConfig.registerDefaultValueProcessor(Integer.class,  
		    new DefaultValueProcessor(){  
		        public Object getDefaultValue(Class type){  
		            return JSONNull.getInstance();  
		        }  
		    });  
		
		JSONObject pdJO = JSONObject.fromObject(map,jsonConfig);
		
		//log.info("pdJSON: "+pdJO);
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(pdJO);
			
	}

	@RequestMapping("saveFirstPD")
	public void saveFirstPD(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String custId = request.getSession().getAttribute("ratingCustId").toString();
		String pdId = request.getSession().getAttribute("pdId").toString();
		PdH pdH = new PdH();
		pdH = ratingService.findPDById(pdId);
		pdH.setFirstDate(CalendarUtil.getCurrentDateStr());
		pdH.setFirstReason(request.getParameter("firstReason"));
		String pdValue = request.getParameter("firstPdlevel");
		
		boolean isDouble=pdValue.matches("^[-\\+]?\\d*(\\.\\d*)?$");
		
		//如果PD是String类型，直接set
		if(!isDouble){
			pdH.setFirstPdlevel(pdValue);
			Double pd = Double.valueOf(DataDictionary.getInstance().getDataDictionary().get("PDValue").get(pdValue).getItemName());
			pdH.setFirstPdvalue(pd);
		}
		//如果PD是数值，通过PD值去找AAA
		else{
			String type = "PDValue";
			Map<String, CodeLib> addType = new LinkedHashMap<String, CodeLib>();
			addType=DataDictionary.getInstance().getDataDictionary().get(type);
			Iterator iter = addType.entrySet().iterator(); 
			String pdLevel = "";
			while (iter.hasNext()) { 
			    Map.Entry entry = (Map.Entry) iter.next(); 
			    String addTypeCode = (String) entry.getKey(); 
			    String addTypeName = ((CodeLib)entry.getValue()).getItemName();
			    if(addTypeName.equals(pdValue)){
			    	pdLevel = addTypeCode;
			    }
			}
			pdH.setFirstPdlevel(pdLevel);
			pdH.setFirstPdvalue(Double.valueOf(pdValue));
		}
		
		
		//如果是零售客户
		String modelId = request.getSession().getAttribute("usedModelId").toString();
		ModelHis model = modelService.findModelHisById(modelId);
		if(model!=null && model.getModelKind1().equals("04")){
			pdH.setFirstPdlevel(pdValue);
			pdH.setFirstPdvalue(Double.valueOf(pdValue));
		}
		
		UserInfo userInfo  =  (UserInfo) request.getSession().getAttribute("logonUser");
		if(userInfo!=null){
			pdH.setFirstUserId(userInfo.getUserId());
			OrgInfo org = (OrgInfo) request.getSession().getAttribute("logonUserOrg");
			if(org!=null)
				pdH.setFirstOrgId(org.getOrgId());
		}
		ratingService.updatePdH(pdH);	
		//log.info("初评保存成功");

		Map map = new HashMap();
		map.put("success", true);
		map.put("data", pdH);
		
		JsonConfig jsonConfig= new JsonConfig();  
		jsonConfig.registerDefaultValueProcessor(Integer.class,  
		    new DefaultValueProcessor(){  
		        public Object getDefaultValue(Class type){  
		            return JSONNull.getInstance();  
		        }  
		    });  
		
		JSONObject pdJO = JSONObject.fromObject(map,jsonConfig);
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(pdJO);
		
		//log.info("JSON： "+pdJO);
	}
	
	//通过系统评级结果获得PD值
	@RequestMapping("commitFirstPD")
	public void commitFirstPD(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String custId = request.getSession().getAttribute("ratingCustId").toString();
		//如果是零售客户
		String modelId = request.getSession().getAttribute("usedModelId").toString();
		ModelHis model = modelService.findModelHisById(modelId);
			
		String pdId = request.getSession().getAttribute("pdId").toString();
		PdH pdH = new PdH();
		pdH = ratingService.findPDById(pdId);
		if(model!=null && model.getModelKind1().equals("04")){
			pdH.setPhaseStat("03");
		}else{
			pdH.setPhaseStat("02");
		}

		ratingService.updatePdH(pdH);	
		//log.info("初评提交成功");
		
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		JSONObject JO=JSONObject.fromObject(pdH);
		out.print(JO);
	}
	
	
	/*
	 * 复评
	 */

	
	@RequestMapping("saveFirstVerifyPD")
	public void saveFirstVerifyPD(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String custId = request.getSession().getAttribute("ratingCustId").toString();
		String pdId = request.getSession().getAttribute("pdId").toString();
		PdH pdH = new PdH();
		pdH = ratingService.findPDById(pdId);
		pdH.setFirstVerifyDate(CalendarUtil.getCurrentDateStr());
		pdH.setFirstVerifyReason(request.getParameter("firstVerifyReason"));
		String pdValue = request.getParameter("firstVerifyPdlevel");
		
		boolean isDouble=pdValue.matches("^[-\\+]?\\d*(\\.\\d*)?$");
		
		//如果PD是String类型，直接set
		if(!isDouble){
			pdH.setFirstVerifyPdlevel(pdValue);
			Double pd = Double.valueOf(DataDictionary.getInstance().getDataDictionary().get("PDValue").get(pdValue).getItemName());
			pdH.setFirstVerifyPdvalue(pd);
		}
		//如果PD是数值，通过PD值去找AAA
		else{
			String type = "PDValue";
			Map<String, CodeLib> addType = new LinkedHashMap<String, CodeLib>();
			addType=DataDictionary.getInstance().getDataDictionary().get(type);
			Iterator iter = addType.entrySet().iterator(); 
			String pdLevel = "";
			while (iter.hasNext()) { 
			    Map.Entry entry = (Map.Entry) iter.next(); 
			    String addTypeCode = (String) entry.getKey(); 
			    String addTypeName = ((CodeLib)entry.getValue()).getItemName();
			    if(addTypeName.equals(pdValue)){
			    	pdLevel = addTypeCode;
			    }
			}
			pdH.setFirstVerifyPdlevel(pdLevel);
			pdH.setFirstVerifyPdvalue(Double.valueOf(pdValue));
		}

		//如果是零售客户
		String modelId = request.getSession().getAttribute("usedModelId").toString();
		ModelHis model = modelService.findModelHisById(modelId);
		if(model!=null && model.getModelKind1().equals("04")){
			pdH.setFirstVerifyPdlevel(pdValue);
			
		}
		UserInfo userInfo  =  (UserInfo) request.getSession().getAttribute("logonUser");
		if(userInfo!=null){
			pdH.setFirstVerifyUserId(userInfo.getUserId());
			OrgInfo org = (OrgInfo) request.getSession().getAttribute("logonUserOrg");
			if(org!=null)
				pdH.setFirstVerifyOrgId(org.getOrgId());
		}
		
		ratingService.updatePdH(pdH);	
		//log.info("复评保存成功");

		Map map = new HashMap();
		map.put("success", true);
		map.put("data", pdH);
		
		JsonConfig jsonConfig= new JsonConfig();  
		jsonConfig.registerDefaultValueProcessor(Integer.class,  
		    new DefaultValueProcessor(){  
		        public Object getDefaultValue(Class type){  
		            return JSONNull.getInstance();  
		        }  
		    });  
		
		JSONObject pdJO = JSONObject.fromObject(map,jsonConfig);
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(pdJO);
	}
	
	//通过系统评级结果获得PD值
	@RequestMapping("commitFirstVerifyPD")
	public void commitFirstVerifyPD(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String custId = request.getSession().getAttribute("ratingCustId").toString();
		String pdId = request.getSession().getAttribute("pdId").toString();
		PdH pdH = new PdH();
		pdH = ratingService.findPDById(pdId);
		pdH.setPhaseStat("03");
		ratingService.updatePdH(pdH);	
		//log.info("复评提交成功");
		
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		JSONObject JO=JSONObject.fromObject(pdH);
		out.print(JO);
	}
	
	
	//退回初评人
	@RequestMapping("returnToFirst")
	public void returnToFirst(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String custId = request.getSession().getAttribute("ratingCustId").toString();
		String pdId = request.getSession().getAttribute("pdId").toString();
		PdH pdH = new PdH();
		pdH = ratingService.findPDById(pdId);
		pdH.setPhaseStat("07");
		ratingService.updatePdH(pdH);	
		//log.info("退回初评成功");
		
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		JSONObject JO=JSONObject.fromObject(pdH);
		out.print(JO);
	}
	
	/*
	 * 审核
	 */
	
	@RequestMapping("saveSecondPD")
	public void saveSecondPD(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String custId = request.getSession().getAttribute("ratingCustId").toString();
		String pdId = request.getSession().getAttribute("pdId").toString();
		PdH pdH = new PdH();
		pdH = ratingService.findPDById(pdId);
		pdH.setSecondDate(CalendarUtil.getCurrentDateStr());
		pdH.setSecondReason(request.getParameter("secondReason"));
		String pdValue = request.getParameter("secondPdlevel");
		String secondIdentify = request.getParameter("secondIdentify");

		pdH.setSecondIdentify(secondIdentify);
		
		boolean isDouble=pdValue.matches("^[-\\+]?\\d*(\\.\\d*)?$");
		String pdLevel = pdValue;
		//如果PD是String类型，直接set
		if(!isDouble){
			pdH.setFirstVerifyPdlevel(pdValue);
			Double pd = Double.valueOf(DataDictionary.getInstance().getDataDictionary().get("PDValue").get(pdValue).getItemName());
			pdH.setFirstVerifyPdvalue(pd);
		}
		//如果PD是数值，通过PD值去找AAA
		else{
			if(pdValue!=null && !pdValue.equals("")){
				String type = "PDValue";
				Map<String, CodeLib> addType = new LinkedHashMap<String, CodeLib>();
				addType=DataDictionary.getInstance().getDataDictionary().get(type);
				Iterator iter = addType.entrySet().iterator(); 
				while (iter.hasNext()) { 
				    Map.Entry entry = (Map.Entry) iter.next(); 
				    String addTypeCode = (String) entry.getKey(); 
				    String addTypeName = ((CodeLib)entry.getValue()).getItemName();
				    if(addTypeName.equals(pdValue)){
				    	pdLevel = addTypeCode;
				    }
				}
				pdH.setSecondPdlevel(pdLevel);
				pdH.setSecondPdvalue(Double.valueOf(pdValue));
			}
		}
			
		//如果是零售客户
		String modelId = request.getSession().getAttribute("usedModelId").toString();
		ModelHis model = modelService.findModelHisById(modelId);
		if(model!=null && model.getModelKind1().equals("04")){
			if(pdValue != null && !pdValue.equals(""))pdLevel = DataDictionary.getInstance().getNameByCodeAndId("IndSystemResult", pdValue);
			pdH.setSecondPdlevel(pdValue);
			IndInfo indInfo = customerService.findIndCustByCustId(custId);
			indInfo.setCreditLevel(pdLevel);
			customerService.updateIndCustInfo(indInfo);
		}
		
		
		
		UserInfo userInfo  =  (UserInfo) request.getSession().getAttribute("logonUser");
		if(userInfo!=null){
			pdH.setSecondUserId(userInfo.getUserId());
			OrgInfo org = (OrgInfo) request.getSession().getAttribute("logonUserOrg");
			if(org!=null)
				pdH.setSecondOrgId(org.getOrgId());
		}
		ratingService.updatePdH(pdH);	
		//log.info("审核保存成功");

		Map map = new HashMap();
		map.put("success", true);
		map.put("data", pdH);
		
		JsonConfig jsonConfig= new JsonConfig();  
		jsonConfig.registerDefaultValueProcessor(Integer.class,  
		    new DefaultValueProcessor(){  
		        public Object getDefaultValue(Class type){  
		            return JSONNull.getInstance();  
		        }  
		    });  
		
		JSONObject pdJO = JSONObject.fromObject(map,jsonConfig);
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(pdJO);
	}
	
	//通过系统评级结果获得PD值
	@RequestMapping("commitSecondPD")
	public void commitSecondPD(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String custId = request.getSession().getAttribute("ratingCustId").toString();
		String pdId = request.getSession().getAttribute("pdId").toString();
		PdH pdH = new PdH();
		//如果是零售客户
		String modelId = request.getSession().getAttribute("usedModelId").toString();
		ModelHis model = modelService.findModelHisById(modelId);
		
		pdH = ratingService.findPDById(pdId);
		
		if(model!=null && model.getModelKind1().equals("04")){
			pdH.setPhaseStat("06");
		}else{
			pdH.setPhaseStat("04");
			
		}
		
		ratingService.updatePdH(pdH);	
		//log.info("审核提交成功");
		
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		JSONObject JO=JSONObject.fromObject(pdH);
		out.print(JO);
	}
	
	@RequestMapping("saveConfirmPD")
	public void saveConfirmPD(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String custId = request.getSession().getAttribute("ratingCustId").toString();
		String pdId = request.getSession().getAttribute("pdId").toString();
		PdH pdH = new PdH();
		pdH = ratingService.findPDById(pdId);
		pdH.setConfirmDate(CalendarUtil.getCurrentDateStr());
		pdH.setConfirmReason(request.getParameter("confirmReason"));
		String pdValue = request.getParameter("confirmPdlevel");
		
		boolean isDouble=pdValue.matches("^[-\\+]?\\d*(\\.\\d*)?$");
		String pdLevel = pdValue;
		//如果PD是String类型，直接set
		if(!isDouble){
			pdH.setConfirmPdlevel(pdValue);
			Double pd = Double.valueOf(DataDictionary.getInstance().getDataDictionary().get("PDValue").get(pdValue).getItemName());
			pdH.setConfirmPdvalue(pd);
		}
		//如果PD是数值，通过PD值去找AAA
		else{
			String type = "PDValue";
			Map<String, CodeLib> addType = new LinkedHashMap<String, CodeLib>();
			addType=DataDictionary.getInstance().getDataDictionary().get(type);
			Iterator iter = addType.entrySet().iterator(); 
			while (iter.hasNext()) { 
			    Map.Entry entry = (Map.Entry) iter.next(); 
			    String addTypeCode = (String) entry.getKey(); 
			    String addTypeName = ((CodeLib)entry.getValue()).getItemName();
			    if(addTypeName.equals(pdValue)){
			    	pdLevel = addTypeCode;
			    }
			}
			pdH.setConfirmPdlevel(pdLevel);
			pdH.setConfirmPdvalue(Double.valueOf(pdValue));
		}
		//如果是零售客户
		String modelId = request.getSession().getAttribute("usedModelId").toString();
		ModelHis model = modelService.findModelHisById(modelId);
		if(model!=null && model.getModelKind1().equals("04")){
			pdH.setConfirmPdlevel(pdValue);
			
		}
		UserInfo userInfo  =  (UserInfo) request.getSession().getAttribute("logonUser");
		if(userInfo!=null){
			pdH.setConfirmUserId(userInfo.getUserId());
			OrgInfo org = (OrgInfo) request.getSession().getAttribute("logonUserOrg");
			if(org!=null)
				pdH.setConfirmOrgId(org.getOrgId());
		}
		ratingService.updatePdH(pdH);	
		
		//将PDlevel写入客户基本信息
		CustInfo custInfo = customerService.findCustByCustId(custId);
		if(custInfo != null){
			custInfo.setCreditLevel(pdLevel);
			customerService.updateCustInfo(custInfo);
		}else{
			IndInfo indInfo = customerService.findIndCustByCustId(custId);
			indInfo.setCreditLevel(pdLevel);
			customerService.updateIndCustInfo(indInfo);
		}
		//log.info("认定保存成功");

		Map map = new HashMap();
		map.put("success", true);
		map.put("data", pdH);
		
		JsonConfig jsonConfig= new JsonConfig();  
		jsonConfig.registerDefaultValueProcessor(Integer.class,  
		    new DefaultValueProcessor(){  
		        public Object getDefaultValue(Class type){  
		            return JSONNull.getInstance();  
		        }  
		    });  
		
		JSONObject pdJO = JSONObject.fromObject(map,jsonConfig);
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(pdJO);
	}	
	
	@RequestMapping("commitConfirmPD")
	public void commitConfirmPD(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		String custId = request.getSession().getAttribute("ratingCustId").toString();
		String pdId = request.getSession().getAttribute("pdId").toString();
		PdH pdH = new PdH();
		pdH = ratingService.findPDById(pdId);
		pdH.setPhaseStat("06");
		ratingService.updatePdH(pdH);	
		//log.info("认定提交成功");

		Map map = new HashMap();
		map.put("success", true);
		map.put("data", pdH);
		
		JsonConfig jsonConfig= new JsonConfig();  
		jsonConfig.registerDefaultValueProcessor(Integer.class,  
		    new DefaultValueProcessor(){  
		        public Object getDefaultValue(Class type){  
		            return JSONNull.getInstance();  
		        }  
		    });  
		
		JSONObject pdJO = JSONObject.fromObject(map,jsonConfig);
		response.setContentType("application/json; charset=utf-8");  
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.print(pdJO);
	}	
	
//	@RequestMapping("refleshRatingResult")
//	public void refleshRatingResult(HttpServletRequest request,
//			HttpServletResponse response) throws IOException{
//		String flag = request.getParameter("flag").toString();
//		request.getSession().removeAttribute("resultFlag");
//		request.getSession().setAttribute("resultFlag", flag);
//		
//		response.getWriter().print("{success:true}");
//	}	
}
